using System; using System.Configuration; using System.Net.Mail; namespace ServiceMe.Apps.Business.Common.Unity { /// <summary> /// 發送郵件幫助類 /// </summary> public class MailHelper { /// <summary> /// 郵箱用戶名 /// </summary> private static readonly string mailUserName = ConfigurationManager.AppSettings["MailUserName"]; /// <summary> /// 郵箱密碼 /// </summary> private static readonly string mailUserPassword = ConfigurationManager.AppSettings["MailUserPassword"]; /// <summary> /// 郵件服務器 /// </summary> private static readonly string emailServer= ConfigurationManager.AppSettings["EmailServer"]; /// <summary> /// 設置爲true容許安全鏈接本地客戶端發送郵件 , 設置爲false不容許容許安全鏈接本地客戶端發送郵件 /// </summary> private static readonly string enableSsl = ConfigurationManager.AppSettings["EnableSsl"]; /// <summary> /// 發送EMAIL /// </summary> /// <param name="sRecipientEmail">收件人地址</param> /// <param name="sSubject">主題</param> /// <param name="sMessage">內容</param> /// <param name="sSendName">發件人名稱</param> /// <returns>發送是否成功</returns> public static bool SendMail(string sRecipientEmail, string sSubject, string sMessage) { try { //郵件對象 MailMessage emailMessage; //smtp客戶端對象 SmtpClient client; string sSenderEmail = mailUserName; emailMessage = new MailMessage(sSenderEmail, sRecipientEmail, sSubject, sMessage); emailMessage.IsBodyHtml = true; emailMessage.SubjectEncoding = System.Text.Encoding.Default; emailMessage.BodyEncoding = System.Text.Encoding.Default; //加入 emailMessage.Headers.Add("X-Priority", "3"); emailMessage.Headers.Add("X-MSMail-Priority", "Normal"); emailMessage.Headers.Add("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869"); emailMessage.Headers.Add("X-MimeOLE", "Produced By Microsoft MimeOLE V6.00.2900.2869"); emailMessage.Headers.Add("ReturnReceipt", "1"); //郵件發送客戶端 client = new SmtpClient(); //郵件服務器及賬戶信息 client.Host = emailServer; //client.Host = "smtp.163.com"; //client.Port = 465; //client.EnableSsl = true; System.Net.NetworkCredential Credential = new System.Net.NetworkCredential(); //web.config中讀取郵件服務器用戶名和密碼信息 Credential.UserName = mailUserName; Credential.Password = mailUserPassword; client.Credentials = Credential; client.EnableSsl =Convert.ToBoolean(enableSsl); //發送郵件 client.Send(emailMessage); } catch(Exception ex) { //錯誤處理待定 Log4NetHelper.WriteError($"發送郵件錯誤信息:{ex.Message},\r\n堆棧信息:{ex.StackTrace}"); return false; } return true; } } }
<appSettings> <!--跨域配置--> <add key="cors_allowOrigins" value="*" /> <add key="cors_allowHeaders" value="*" /> <add key="cors_allowMethods" value="*" /> <add key="EmailServer" value="smtp.office365.com"/> <add key="EnableSsl" value="true"/> <add key="MailUserName" value="xiaogang.tang@medalsoft.com" /> <add key="MailUserPassword" value="HYqdp776" /> </appSettings>
MailHelper.SendMail("xxxx@qq.com", "測試郵件", "請注意,這是一封.NET自動使用OutLook發送的測試郵件!");