C# 多种方式发送邮件(附帮助类)
因项目业务需要,需要做一个发送邮件功能,查了下资料,整了整,汇总如下,亲测可用~
QQ邮箱发送邮件
#region 发送邮箱 try { MailMessage mail = new MailMessage(); MailAddress from = new MailAddress("发件人邮箱", "工程管理平台", System.Text.Encoding.GetEncoding("GB2312"));//邮件的发件人 mail.From = from; MailAddress to = new MailAddress("收件人邮箱");//设置邮件的收件人 mail.To.Add(to); mail.Subject = "收款确认"; string url = "http://wwww.baidu.com"; mail.Body = "您好,有新的待确认收款" + url; mail.IsBodyHtml = true;//HTML格式,内容可以包含HMTL标签和超链接uuu mail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置邮件的格式 mail.Priority = MailPriority.Normal;//设置邮件的发送级别 mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess; SmtpClient client = new SmtpClient();//邮件发送服务器 //client.Port = 25; QQ发送邮件不用设置 client.Host = "smtp.qq.com"; //发件人地址所在的服务器SMTP 如网易126邮箱的为smtp.126.com client.EnableSsl = true; client.UseDefaultCredentials = false; //设置用于 SMTP 事务的端口,默认的是 25 client.Credentials = new System.Net.NetworkCredential("发件人邮箱", "授权码");//发件人邮箱登陆名和密码(生成的授权码) client.DeliveryMethod = SmtpDeliveryMethod.Network; try { client.Send(mail);//发送邮件 MessageShow("发送成功"); Response.Write("<script language='javascript'>alert('发送成功!');</script>"); } catch (System.Net.Mail.SmtpException ex) { MessageShow(ex.Message); } } catch (Exception ex) { throw ex; } #endregion
效果:
注意
重要引用:
using System.Net.Mail;
其中,使用QQ发送邮件,需要使用授权码而不是QQ密码,授权码具体生成方式可以查看:http://service.mail.qq.com/cgi-bin/help?subtype=1&&no=1001256&&id=28
自定义发送邮件
附帮助类的发送邮件方式(推荐此种方式,更灵活)
邮件帮助类
1 #region 邮件帮助类 2 /// <summary> 3 /// 邮件帮助类 4 /// </summary> 5 public static class SendMailHelper 6 { 7 /// <summary> 8 /// 发送邮件 9 /// </summary> 10 /// <param name="request">邮件内容对象</param> 11 /// <returns>发送邮件所遇到的异常</returns> 12 public static string SendMail(MailRequest request) 13 { 14 try 15 { 16 MailMessage mail = new MailMessage(); 17 18 if (string.IsNullOrEmpty(request.From)) 19 { 20 request.From = ConfigurationManager.AppSettings["DefaultMailFrom"]; 21 } 22 mail.From = new MailAddress(request.From); 23 24 PaserMailAddress(request.To, mail.To); 25 PaserMailAddress(request.CC, mail.CC); 26 PaserMailAddress(request.Bcc, mail.Bcc); 27 28 mail.Subject = request.Subject; 29 mail.SubjectEncoding = System.Text.Encoding.UTF8; 30 mail.Body = request.Body; 31 mail.ReplyTo = new MailAddress(request.From); 32 mail.IsBodyHtml = true; 33 34 if (request.Attachments != null && request.Attachments.Length > 0) 35 { 36 for (int i = 0; i < request.Attachments.Length; i++) 37 { 38 Attachment mailAttach = new Attachment(ByteArrayToStream(request.Attachments[i].FileData), request.Attachments[i].FileName); 39 40 mail.Attachments.Add(mailAttach); 41 } 42 } 43 44 if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["SMTPSERVER_Show"])) 45 { 46 throw new ApplicationException("邮件服务无效"); 47 } 48 49 //Smtp Server 50 SmtpClient mailClient = new SmtpClient(ConfigurationManager.AppSettings["SMTPSERVER_Show"]); 51 52 if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["SMTPSERVERPORT"])) 53 { 54 //端口号 55 try 56 { 57 mailClient.Port = Int32.Parse(ConfigurationManager.AppSettings["SMTPSERVERPORT"]); 58 } 59 catch 60 { 61 return "SMTP服务器端口设置错误,端口必须设置为数值型"; 62 } 63 } 64 65 if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["MAILUSER_Show"])) 66 { 67 mailClient.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["MAILUSER_Show"], ConfigurationManager.AppSettings["MAILUSERPW_Show"]); 68 mailClient.DeliveryMethod = SmtpDeliveryMethod.Network; 69 } 70 else 71 { 72 mailClient.Credentials = CredentialCache.DefaultNetworkCredentials; 73 } 74 75 mailClient.Send(mail); 76 mail.Dispose(); 77 78 return string.Empty; 79 } 80 catch (SmtpFailedRecipientsException e) 81 { 82 return e.Message; 83 } 84 catch (SmtpFailedRecipientException e) 85 { 86 return e.Message; 87 } 88 catch (SmtpException e) 89 { 90 return e.Message; 91 } 92 catch (Exception e) 93 { 94 return e.Message; 95 } 96 } 97 98 /// <summary> 99 /// 解析分解邮件地址 100 /// </summary> 101 /// <param name="mailAddress">邮件地址</param> 102 /// <param name="mailCollection">邮件对象</param> 103 private static void PaserMailAddress(string mailAddress, MailAddressCollection mailCollection) 104 { 105 if (string.IsNullOrEmpty(mailAddress)) 106 { 107 return; 108 } 109 110 char[] separator = new char[2] { ',', ';' }; 111 string[] addressArray = mailAddress.Split(separator); 112 113 foreach (string address in addressArray) 114 { 115 if (address.Trim() == string.Empty) 116 { 117 continue; 118 } 119 120 mailCollection.Add(new MailAddress(address)); 121 } 122 } 123 124 /// <summary> 125 /// 字节数组转换为流 126 /// </summary> 127 /// <param name="byteArray">字节数组</param> 128 /// <returns>Stream</returns> 129 private static Stream ByteArrayToStream(byte[] byteArray) 130 { 131 MemoryStream mstream = new MemoryStream(byteArray); 132 133 return mstream; 134 } 135 } 136 #endregion
补充上述帮助类中,还需要添加 MailRequest.cs 类(发送请求相关类) 和 MailRequestAttachments.cs 类(附件类)
MailRequest.cs 类
using System; using System.Collections.Generic; using System.Text; namespace SyncAdData.DBHelper { /// <summary> /// 发送邮件请求 /// </summary> public class MailRequest { #region PrivateFields /// <summary> /// 文件名 /// </summary> private string _fromField; /// <summary> /// 返送到 /// </summary> private string _toField; /// <summary> /// 抄送 /// </summary> private string _copyField; /// <summary> /// 附件 /// </summary> private string _bccField; /// <summary> /// 标题 /// </summary> private string _subjectField; /// <summary> /// 发送人名 /// </summary> private string _bodyField; /// <summary> /// 类容 /// </summary> private MailRequestAttachments[] _attachmentsField; #endregion /// <summary> /// 发送人,多个人以分号;间隔 /// </summary> public string From { get { return this._fromField; } set { this._fromField = value; } } /// <summary> /// 收件人,多个人以分号;间隔 /// </summary> public string To { get { return this._toField; } set { this._toField = value; } } /// <summary> /// 抄送人,多个人以分号;间隔 /// </summary> public string CC { get { return this._copyField; } set { this._copyField = value; } } /// <summary> /// 秘密抄送人,多个人以分号;间隔 /// </summary> public string Bcc { get { return this._bccField; } set { this._bccField = value; } } /// <summary> /// 主题 /// </summary> public string Subject { get { return this._subjectField; } set { this._subjectField = value; } } /// <summary> /// 内容 /// </summary> public string Body { get { return this._bodyField; } set { this._bodyField = value; } } /// <summary> /// 附件列表 /// </summary> public MailRequestAttachments[] Attachments { get { return this._attachmentsField; } set { this._attachmentsField = value; } } } }
MailRequestAttachments.cs 类
using System; using System.Collections.Generic; using System.Text; namespace SyncAdData.DBHelper { /// <summary> /// 发送邮件请求附件 /// </summary> public class MailRequestAttachments { #region PrivateFields /// <summary> /// 文件名 /// </summary> private string _fileNameField; /// <summary> /// 文件内容 /// </summary> private byte[] _fileDataField; #endregion /// <summary> /// 文件名 /// </summary> public string FileName { get { return this._fileNameField; } set { this._fileNameField = value; } } /// <summary> /// 文件内容 /// </summary> public byte[] FileData { get { return this._fileDataField; } set { this._fileDataField = value; } } } }
需要的命名空间
using System; using System.Reflection; using System.Net.Mail; using System.Web.Configuration; using System.Net; using System.IO;
其中 帮助类中的服务器地址 和 账号 密码需要在配置文件中配置
<add key="SMTPSERVER" value="邮件服务器"/> <add key="MAILUSER" value="账号"/> <add key="MAILUSERPW" value="密码"/>
前台调用
/// <summary> /// 发送邮件 /// </summary> /// <param name="StrUrl">根据业务需要,这里我需要传入几个拼接后的id值</param> /// <param name="bid">根据业务需要,这里我传的批次id</param> /// <param name="showemail">根据业务需要,这里我传入的是查询出来的收件人邮箱(如果是固定的更好,可以直接写死或者写成配置文件)</param> private void Send(string StrUrl,string bid,string showemail) { #region 读取配置发送邮件 string url = "http://localhost:9998/FinanceManage/CollectionManage/ConfirmCollection_Receipt.aspx?MenuID=14010600&id=" + StrUrl + "&batchID=" + bid + ""; string body = "您好,有新的待确认收款≥ "+url; //string bcc = string.Empty; string to = "v-zhangxy52@vanke.com";//收件人 //string cc = "";//抄送人 MailRequest mail = new MailRequest(); mail.Subject = "收款确认";//主题 mail.Body = body;//内容 // mail.Bcc = bcc;//秘密抄送人 mail.From = "v-tangqq02@vanke.com";//发送人 mail.To = to; //收件人 // mail.CC = cc; //抄送人 string sendMainResult = "-1"; if (!string.IsNullOrEmpty(mail.To.Trim()) || !string.IsNullOrEmpty(mail.CC.Trim())) { sendMainResult = SendMailHelper.SendMail(mail); if (string.IsNullOrEmpty(sendMainResult)) { BaseClass.CommFun.Alert(this.up_innerCheck, "发送成功!", Page); } } #endregion }
效果
点击确定发送之后,查看邮箱,即可看到发送内容(可根据业务需求自行调整)
刚好另一个项目中也需要用到发邮件,也是用的上述的帮助类,附效果图
至此,发送邮件功能已经全部完毕,当中不乏可以优化的地方,欢迎大家自行优化,相互交流~
- 感谢你的阅读。如果你觉得这篇文章对你有帮助或者有启发,就请推荐一下吧~你的精神支持是博主强大的写作动力。欢迎转载!
- 博主的文章没有高度、深度和广度,只是凑字数。由于博主的水平不高(其实是个菜B),不足和错误之处在所难免,希望大家能够批评指出。
- 欢迎加入.NET 从入门到精通技术讨论群→523490820 期待你的加入
- 不舍得打乱,就永远学不会复原。被人嘲笑的梦想,才更有实现的价值。
- 我的博客:http://www.cnblogs.com/zhangxiaoyong/