2023-05-28 更新,添加文件(附件)发送功能
2022-01-05 更新(视频讲解地址 https://www.bilibili.com/video/BV1Eq4y127SH/ )
/// <summary> /// 邮件发送方法 /// </summary> /// <param name="toMial">收件人邮箱</param> /// <param name="fromMial">发件人邮箱</param> /// <param name="userID">发件人邮箱帐号 如QQ邮箱 为QQ号码 </param> /// <param name="userPwd">发件人邮箱受权码</param> /// <param name="serverAddress">邮件服务地址 如QQ邮箱服务地址为smtp.qq.com</param> /// <param name="subject">邮件主题</param> /// <param name="body">邮件内容</param> /// <param name="filePath">文件位置</param> /// <returns></returns> public bool MailSender(string toMial, string fromMial, string userID, string userPwd, string serverAddress, string subject, string body,string filePath="") {//更多源码请访问 www.luofenming.com try { //创建一个邮件对像 MailMessage mailObject = new MailMessage(); //设置发件人 mailObject.From = new MailAddress(fromMial); //设置收件人 mailObject.To.Add(new MailAddress(toMial)); //设置邮件主题 mailObject.SubjectEncoding = Encoding.UTF8; mailObject.Subject = subject; //设置邮件内容 mailObject.BodyEncoding = Encoding.UTF8;//编码 mailObject.Body = body; //发送文件(附件) if (string.IsNullOrEmpty(filePath)) {//附件地址为空时 则不发送 Attachment amen = new Attachment(@"C:\Users\lqwvje\Desktop\新建文本文档.txt"); mailObject.Attachments.Add(amen); } //创建一个发送邮件的对像 SmtpClient smtpClient = new SmtpClient(); //服务地址 如QQ邮箱 smtp.qq.com smtpClient.Host = serverAddress; //帐号和受权码 smtpClient.Credentials = new NetworkCredential(userID, userPwd); smtpClient.Send(mailObject); return true; } catch (Exception ex) { throw (ex); } }
方法调用
MailSender("lqwvje@163.com", "78630559@qq.com", "78630559", "受权码", "smtp.qq.com", "测试发送邮件主题", "测试发送邮件内容",@"C:\Users\lqwvje\Desktop\新建文本文档.txt");
本文出自 www.luofenming.com