C# 多种方式发送邮件(附帮助类)
生活随笔
收集整理的這篇文章主要介紹了
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.comclient.EnableSsl = true;client.UseDefaultCredentials = false; //設置用于 SMTP 事務的端口,默認的是 25client.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 View Code?
補充上述幫助類中,還需要添加?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;}}} } View Code?
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;}}} } View Code?
需要的命名空間
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 }?
效果
?點擊確定發送之后,查看郵箱,即可看到發送內容(可根據業務需求自行調整)
?
?剛好另一個項目中也需要用到發郵件,也是用的上述的幫助類,附效果圖
?
?
?至此,發送郵件功能已經全部完畢,當中不乏可以優化的地方,歡迎大家自行優化,相互交流~
轉載于:https://www.cnblogs.com/zhangxiaoyong/p/6117848.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的C# 多种方式发送邮件(附帮助类)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS中self.xxx 和 _xxx
- 下一篇: 失败,因为你其实太过傲慢