c# 兩種發(fā)送郵件的方法
一、兩種發(fā)送郵件的方法
有用到兩種方式發(fā)郵件,一種是用System.Web.Mail類,另一種是System.Net.Mail類。
System.Net.Mail是作為System.Web.Mail的替代存在的。
System.Web.Mail使用時會提示已過時,但目前任然可以正常使用。
二、遇到的問題
我在使用System.Net.Mail發(fā)郵件的時候遇到一個問題,如果是用的阿里云服務(wù)器,阿里云服務(wù)器把郵件的默認(rèn)25端口給禁用掉了(為的是不讓郵件泛濫),25端口被封,阿里云發(fā)送SMTP郵件失敗。
在網(wǎng)上找了一些資料,主要有以下幾種方法解決:
1、在阿里云平臺申請解封TCP 25 端口 (Outbound)
2、更換端口號為465 或 587 ;
3、服務(wù)器前綴加上 ssl://
4、使用System.Web.Mail發(fā)送郵件
2和3我都試用無果,阿里云服務(wù)器還是發(fā)送郵件失敗,最后使用System.Web.Mail發(fā)送成功,要是有別的更好的方法請大家告知,謝謝謝謝~~
三、示例
這里我把發(fā)郵件一些相關(guān)的參數(shù)配置在ini文件里(smt服務(wù)器、端口號、發(fā)件人郵箱、發(fā)件人密碼、發(fā)件人昵稱、接收人郵箱)
#region 讀寫本地IN文件 public static string ReadIniFile(string iniFileName, string section, string key) { string strFileName = GetRootPath() + "\\" + iniFileName; if (!System.IO.File.Exists(strFileName)) { FileStream fs = System.IO.File.Create(strFileName); fs.Close(); } TWays.IniFile localIniFile = new TWays.IniFile(strFileName); return localIniFile.ReadInivalue(section, key); } public static void WriteIniFile(string iniFileName, string section, string key, string value) { string strFileName = GetRootPath() + "\\" + iniFileName; if (!System.IO.File.Exists(strFileName)) { FileStream fs = System.IO.File.Create(strFileName); fs.Close(); } TWays.IniFile localIniFile = new TWays.IniFile(strFileName); localIniFile.WriteInivalue(section, key, value); } #endregion public const string MonitorLogFileName = "WmsImportSheetLog.Log"; public const string MailSetIniFileName = "MailSet.ini"; public const string MailSetSectionOption = "Option"; public const string MailSetKeySmtpServer = "SmtpServer";//smtp服務(wù)器 public const string MailSetKeySmtpPort = "SmtpPort";//端口號 public const string MailSetKeySendAddr = "SendAddr";//發(fā)件人郵箱 public const string MailSetKeySendPwd = "SendPwd";//發(fā)件人密碼 public const string MailSetKeySendUser = "SendUser";//發(fā)件人名稱,可隨意定義 public const string MailSetKeyReceiAddr = "ReceiAddr";//收件人郵箱 //如果ini文件內(nèi)沒有內(nèi)容就設(shè)置默認(rèn)值 public void WriteMailSet() { string strFileName = BusiUtils.GetRootPath() + "\\" + Constant.MailSetIniFileName; if (!System.IO.File.Exists(strFileName)) { BusiUtils.WriteIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySmtpServer, "smtp.163.com"); BusiUtils.WriteIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySmtpPort, "465"); BusiUtils.WriteIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendAddr, "lala12121@163.com"); string sendPwd = "lalala2017"; sendPwd = TWays.Utils.EncryptString(sendPwd); BusiUtils.WriteIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendPwd, sendPwd); BusiUtils.WriteIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendUser, "系統(tǒng)管理員"); //多個收件人用 ' ;' 號隔開 BusiUtils.WriteIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeyReceiAddr, "1234@qq.com;5678@qq.com;2579@qq.com;"); } }
System.Web.Mail
public bool Process() { bool boolReturn = false; try { string errorMsg = string.Empty; string title = "每日單據(jù)導(dǎo)入情況" + "-" + DateTime.Now.ToString("yyyy-MM -dd"); string message = string.Empty; try { WriteMailSet(); bool bl = true; DataSet ds = DataAdapter.Query(SqlText.selectImportSheetErrorLog.ToUpper()); #region if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count <= 0) { message = "單據(jù)處理成功!"; } else { StringBuilder sb = new StringBuilder(); sb.Append("以下為單據(jù)導(dǎo)入異常的消息:\r\n\r\n"); foreach (DataRow dr in ds.Tables[0].Rows) { bl = false; sb.Append(" 任務(wù)編號:" + dr["TASK_CODE"].ToString() + ",\t"); sb.Append(" 任務(wù)名稱:" + dr["TASK_NAME"].ToString() + ",\t"); sb.Append(" 日志消息:" + dr["MEMO"].ToString()); sb.Append("\r\n"); } message = sb.ToString(); } #endregion if (bl) { title = "[成功]" + title; } } catch (Exception Ex) { message = Ex.Message; errorMsg = "郵件發(fā)送失敗!錯誤信息:" + message; message = "Error:" + Ex.Message; TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true); return boolReturn; } #region 發(fā)送郵件 try { TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, "發(fā)送" + title + "開始\r\n", true); bool result = Monitor(title, message, "", ""); TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, "發(fā)送" + title + "結(jié)束\r\n", true); } catch (Exception Ex) { errorMsg = "郵件發(fā)送失??!錯誤信息:" + Ex.Message; TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true); return boolReturn; } #endregion Result = "Succeed"; boolReturn = true; } catch (Exception ex) { Result = ex.Message; } return boolReturn; } private bool Monitor(string title, string message, string fileName, string shortFileName) { string smtpServer = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySmtpServer); string smtpPort = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySmtpPort); string sendAddr = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendAddr); string sendPwd = Utils.DecryptString(BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendPwd)); string receiAddr = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeyReceiAddr); string errorMsg = string.Empty; try { System.Web.Mail.MailMessage mmsg = new System.Web.Mail.MailMessage(); //郵件主題 mmsg.Subject = title; //mmsg.BodyFormat = System.Web.Mail.MailFormat.Html; //郵件正文 mmsg.Body = message; //正文編碼 mmsg.BodyEncoding = Encoding.UTF8; //優(yōu)先級 mmsg.Priority = System.Web.Mail.MailPriority.High; System.Web.Mail.MailAttachment data = null; //if (SUpFile != "") //{ // SUpFile = HttpContext.Current.Server.MapPath(SUpFile);//獲得附件在本地地址 // System.Web.Mail.MailAttachment attachment = new System.Web.Mail.MailAttachment(SUpFile); //create the attachment // mmsg.Attachments.Add(attachment); //add the attachment //} //發(fā)件者郵箱地址 mmsg.From = string.Format("\"{0}\"<{1}>", "方予系統(tǒng)管理員", sendAddr); //收件人收箱地址 mmsg.To = receiAddr; mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //用戶名 mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", sendAddr); //密碼 不是郵箱登陸密碼 而是郵箱設(shè)置POP3/SMTP 時生成的第三方客戶端授權(quán)碼 mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", sendPwd); //端口 mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", smtpPort); //使用SSL mmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true"); //Smtp服務(wù)器 System.Web.Mail.SmtpMail.SmtpServer = smtpServer; System.Web.Mail.SmtpMail.Send(mmsg); System.Threading.Thread.Sleep(20000); } catch (Exception Ex) { errorMsg = "郵件發(fā)送失敗!錯誤信息:" + Ex.Message; TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true); return false; } return true; }
System.Net.Mail
SmtpClient SmtpClient = null; //設(shè)置SMTP協(xié)議 MailAddress MailAddress_from = null; //設(shè)置發(fā)信人地址 當(dāng)然還需要密碼 MailAddress MailAddress_to = null; //設(shè)置收信人地址 不需要密碼 MailMessage MailMessage_Mai = null; FileStream FileStream_my = null; //附件文件流 public bool Process() { bool boolReturn = false; try { string errorMsg = string.Empty; string title = "每日單據(jù)導(dǎo)入情況" + "-" + DateTime.Now.ToString("yyyy-MM-dd"); string message = string.Empty; try { WriteMailSet(); bool bl = true; DataSet ds = DataAdapter.Query(SqlText.selectImportSheetErrorLog.ToUpper()); #region if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count <= 0) { message = "單據(jù)導(dǎo)入成功!"; } else { StringBuilder sb = new StringBuilder(); sb.Append("以下為單據(jù)導(dǎo)入異常的消息:\r\n\r\n"); foreach (DataRow dr in ds.Tables[0].Rows) { bl = false; sb.Append(" 任務(wù)編號:" + dr["TASK_CODE"].ToString() + ",\t"); sb.Append(" 任務(wù)名稱:" + dr["TASK_NAME"].ToString() + ",\t"); sb.Append(" 日志消息:" + dr["MEMO"].ToString()); sb.Append("\r\n"); } message = sb.ToString(); } #endregion if (bl) { title = "[成功]" + title; } } catch (Exception Ex) { message = Ex.Message; errorMsg = "郵件發(fā)送失??!錯誤信息:" + message; message = "Error:" + Ex.Message; TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true); return boolReturn; } #region 發(fā)送郵件 try { TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, "發(fā)送" + title + "開始\r\n", true); bool result = Monitor(title, message, "", ""); TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, "發(fā)送" + title + "結(jié)束\r\n", true); } catch (Exception Ex) { errorMsg = "郵件發(fā)送失敗!錯誤信息:" + Ex.Message; TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true); return boolReturn; } #endregion Result = "Succeed"; boolReturn = true; } catch (Exception ex) { Result = ex.Message; } return boolReturn; } private bool Monitor(string title, string message, string fileName, string shortFileName) { string smtpServer = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySmtpServer); string smtpPort = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySmtpPort); string sendAddr = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendAddr); string sendPwd = Utils.DecryptString(BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendPwd)); string receiAddr = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeyReceiAddr); string errorMsg = string.Empty; try { //初始化Smtp服務(wù)器信息 setSmtpClient(smtpServer, Convert.ToInt32(smtpPort)); } catch (Exception Ex) { errorMsg = "郵件發(fā)送失敗,請確定SMTP服務(wù)名是否正確!錯誤信息:" + Ex.Message; TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true); return false; } try { //驗證發(fā)件郵箱地址和密碼 setAddressform(sendAddr, sendPwd); } catch (Exception Ex) { errorMsg = "郵件發(fā)送失敗,請確定發(fā)件郵箱地址和密碼的正確性!錯誤信息:" + Ex.Message; TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true); return false; } try { MailMessage_Mai = null; MailMessage_Mai = new MailMessage(); //清空歷史發(fā)送信息 以防發(fā)送時收件人收到的錯誤信息(收件人列表會不斷重復(fù)) MailMessage_Mai.To.Clear(); string[] recAddress = receiAddr.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); //添加收件人郵箱地址 for (int i = 0; i < recAddress.Length; i++) { MailAddress_to = new MailAddress(recAddress[i]); MailMessage_Mai.To.Add(MailAddress_to); } //發(fā)件人郵箱 MailMessage_Mai.From = MailAddress_from; //郵件主題 MailMessage_Mai.Subject = title; MailMessage_Mai.SubjectEncoding = System.Text.Encoding.UTF8; //郵件正文 MailMessage_Mai.Body = message; MailMessage_Mai.BodyEncoding = System.Text.Encoding.UTF8; //清空歷史附件 以防附件重復(fù)發(fā)送 //MailMessage_Mai.Attachments.Clear(); //FileStream_my = new FileStream(fileName, FileMode.Open); //string name = FileStream_my.Name; ////添加附件 //MailMessage_Mai.Attachments.Add(new Attachment(FileStream_my, shortFileName)); //注冊郵件發(fā)送完畢后的處理事件 SmtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); //開始發(fā)送郵件 SmtpClient.SendAsync(MailMessage_Mai, "000000000"); System.Threading.Thread.Sleep(30000); } catch (Exception Ex) { errorMsg = "郵件發(fā)送失??!錯誤信息:" + Ex.Message; TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true); return false; } return true; } #region 設(shè)置Smtp服務(wù)器信息 /// <summary> /// 設(shè)置Smtp服務(wù)器信息 /// </summary> /// <param name="ServerName">SMTP服務(wù)名</param> /// <param name="Port">端口號</param> private void setSmtpClient(string ServerHost, int Port) { SmtpClient = new SmtpClient(); SmtpClient.Host = ServerHost;//指定SMTP服務(wù)名 例如QQ郵箱為 smtp.qq.com 新浪cn郵箱為 smtp.sina.cn等 SmtpClient.Port = Port; //指定端口號 SmtpClient.Timeout = 5; //超時時間 SmtpClient.EnableSsl = true; //指定 SmtpClient 使用安全套接字層 (SSL) 加密連接 } #endregion #region 驗證發(fā)件人信息 /// <summary> /// 驗證發(fā)件人信息 /// </summary> /// <param name="MailAddress">發(fā)件郵箱地址</param> /// <param name="MailPwd">郵箱密碼</param> private void setAddressform(string MailAddress, string MailPwd) { string sendUser = BusiUtils.ReadIniFile(Constant.MailSetIniFileName, Constant.MailSetSectionOption, Constant.MailSetKeySendUser); //創(chuàng)建服務(wù)器認(rèn)證 NetworkCredential NetworkCredential_my = new NetworkCredential(MailAddress, MailPwd); //實例化發(fā)件人地址 MailAddress_from = new System.Net.Mail.MailAddress(MailAddress, sendUser, Encoding.BigEndianUnicode); //指定發(fā)件人信息 包括郵箱地址和郵箱密碼 SmtpClient.Credentials = new System.Net.NetworkCredential(MailAddress_from.Address, MailPwd); } #endregion #region 發(fā)送郵件后所處理的函數(shù) private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e) { string errorMsg = string.Empty; try { if (e.Cancelled) { errorMsg = "發(fā)送已取消!"; TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true); } if (e.Error != null) { errorMsg = "郵件發(fā)送失?。?錯誤信息:" + e.Error.Message; TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true); } else { errorMsg = "恭喜,郵件成功發(fā)出!"; TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true); } if (FileStream_my != null) { FileStream_my.Close(); } } catch (Exception Ex) { errorMsg = "郵件發(fā)送失?。?錯誤信息:" + Ex.Message; TWays.Core.Loger.LogMessage(BusiUtils.GetRootPath() + "\\" + Constant.MonitorLogFileName, errorMsg + "\r\n", true); } } #endregion
以上就是c# 兩種發(fā)送郵件的方法的詳細(xì)內(nèi)容,更多關(guān)于c# 發(fā)送郵件的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
c# 模擬串口通信 SerialPort的實現(xiàn)示例
本文主要介紹了c# 模擬串口通信 SerialPort的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05.NET創(chuàng)建、刪除、復(fù)制文件夾及其子文件的實例方法
.NET創(chuàng)建、刪除、復(fù)制文件夾及其子文件的實例方法,需要的朋友可以參考一下2013-03-03C#實現(xiàn)字符串進(jìn)制轉(zhuǎn)換方法匯總
這篇文章主要介紹了C#實現(xiàn)字符串進(jìn)制轉(zhuǎn)換方法匯總,給大家羅列了十幾種機(jī)制轉(zhuǎn)換問題,感興趣的朋友跟隨小編一起看看吧2022-11-11c#中Empty()和DefalutIfEmpty()用法分析
這篇文章主要介紹了c#中Empty()和DefalutIfEmpty()用法,以實例形式分析了針對不同情況下Empty()和DefalutIfEmpty()用法區(qū)別,需要的朋友可以參考下2014-11-11WPF中不規(guī)則窗體與WindowsFormsHost控件兼容問題的解決方法
這篇文章主要介紹了WPF中不規(guī)則窗體與WindowsFormsHost控件兼容問題的解決方法,對比以往的解決方案,給出了一個具有普遍性的技巧,具有一定的借鑒價值,需要的朋友可以參考下2014-11-11C#實現(xiàn)為類和函數(shù)代碼自動添加版權(quán)注釋信息的方法
這篇文章主要介紹了C#實現(xiàn)為類和函數(shù)代碼自動添加版權(quán)注釋信息的方法,主要涉及安裝文件的修改及函數(shù)注釋模板的修改,需要的朋友可以參考下2014-09-09