您好,登錄后才能下訂單哦!
發送電子郵件也是項目開發當中經常用到的功能,這里我整理了一個發送電子郵件(帶附件,支持多用戶發送,主送、抄送)的類庫,供大家參考。
先上兩個實體類,用于封裝成Mail對象。
/// <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[] _p_w_uploadsField; #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._p_w_uploadsField; } set { this._p_w_uploadsField = value; } } }
/// <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; } } }
附件的內容很簡單,因為在網絡傳輸當中,是以字節流的形式傳輸的,因此附件的傳輸需要轉換成字節流數組。
/// <summary> /// 郵件幫助類 /// </summary> public static class MailHelper { /// <summary> /// 發送郵件 /// </summary> /// <param name="request">郵件內容對象</param> /// <returns>發送郵件所遇到的異常</returns> public static string SendMail(MailRequest request) { try { MailMessage mail = new MailMessage(); if (string.IsNullOrEmpty(request.From)) { request.From = WebConfigurationManager.AppSettings["DefaultMailFrom"]; } mail.From = new MailAddress(request.From); PaserMailAddress(request.To, mail.To); PaserMailAddress(request.CC, mail.CC); PaserMailAddress(request.Bcc, mail.Bcc); mail.Subject = request.Subject; mail.SubjectEncoding = System.Text.Encoding.UTF8; mail.Body = request.Body; mail.ReplyTo = new MailAddress(request.From); mail.IsBodyHtml = true; if (request.Attachments != null && request.Attachments.Length > 0) { for (int i = 0; i < request.Attachments.Length; i++) { Attachment mailAttach = new Attachment(ByteArrayToStream(request.Attachments[i].FileData), request.Attachments[i].FileName); mail.Attachments.Add(mailAttach); } } if (string.IsNullOrEmpty(WebConfigurationManager.AppSettings["SMTPSERVER"])) { throw new ApplicationException("郵件服務無效"); } //Smtp Server SmtpClient mailClient = new SmtpClient(WebConfigurationManager.AppSettings["SMTPSERVER"]); if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["SMTPSERVERPORT"])) { //端口號 try { mailClient.Port = Int32.Parse(WebConfigurationManager.AppSettings["SMTPSERVERPORT"]); } catch { return "SMTP服務器端口設置錯誤,端口必須設置為數值型"; } } if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings["MAILUSER"])) { mailClient.Credentials = new System.Net.NetworkCredential(WebConfigurationManager.AppSettings["MAILUSER"], WebConfigurationManager.AppSettings["MAILUSERPW"]); mailClient.DeliveryMethod = SmtpDeliveryMethod.Network; } else { mailClient.Credentials = CredentialCache.DefaultNetworkCredentials; } mailClient.Send(mail); mail.Dispose(); return "郵件發送成功。"; } catch (SmtpFailedRecipientsException e) { return e.Message; } catch (SmtpFailedRecipientException e) { return e.Message; } catch (SmtpException e) { return e.Message; } catch (Exception e) { return e.Message; } } /// <summary> /// 解析分解郵件地址 /// </summary> /// <param name="mailAddress">郵件地址</param> /// <param name="mailCollection">郵件對象</param> private static void PaserMailAddress(string mailAddress, MailAddressCollection mailCollection) { if (string.IsNullOrEmpty(mailAddress)) { return; } char[] separator = new char[2] { ',', ';' }; string[] addressArray = mailAddress.Split(separator); foreach (string address in addressArray) { if (address.Trim() == string.Empty) { continue; } mailCollection.Add(new MailAddress(address)); } } /// <summary> /// 字節數組轉換為流 /// </summary> /// <param name="byteArray">字節數組</param> /// <returns>Stream</returns> private static Stream ByteArrayToStream(byte[] byteArray) { MemoryStream mstream = new MemoryStream(byteArray); return mstream; } }
這是一個郵件助手類,定義成static,無需實例化,直接類名.方法名的形式調用。
只需要上述3個類就可以實現發送Email了,由于上面引用的是web.config里面的信息(asp.net等命名空間,如果是winform等需要自己修改一下),這里還需要配置一下web.config,如下所示:
<appSettings> <!--郵件發送配置--> <add key="SMTPSERVER" value="smtp.qq.com"/> <!--這是服務器郵箱的地址,如果是新浪,則填 smtp.sina.com--> <add key="MAILUSER" value="xxx"/> <!--注意!這是對應服務器郵箱的賬號--> <add key="MAILUSERPW" value="yyy"/> <!--注意!這是對應服務器郵箱的賬號密碼--> </appSettings>
最后上一個測試方法,在主函數當中或者Page_Load事件中執行即可:
private void SendEmailExample() { MailRequest mail = new MailRequest(); mail.Subject = "hello,this is a e-mail sent by asp.net mailhelper.";//主題 mail.Body = "hello,this is a e-mail sent by asp.net mailhelper.<a ;//內容 mail.Bcc = "512122338@qq.com";//秘密抄送人 mail.From = "345822155@qq.com";//發送人 mail.CC = "guwei4037@sina.com";//抄送人 mail.To = "guwei4037@gmail.com";//收件人 //讀取文件到bytes FileStream stream = new FileStream(Path.Combine(Server.MapPath("~"), "doc\\test.txt"), FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read); byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); stream.Close(); //附件 MailRequestAttachments p_w_uploads = new MailRequestAttachments(); p_w_uploads.FileName = "test.txt"; p_w_uploads.FileData = bytes; mail.Attachments = new MailRequestAttachments[] { p_w_uploads }; string sendMainResult = "-1"; if (!string.IsNullOrEmpty(mail.CC.Replace(";", "")) && !string.IsNullOrEmpty(mail.To.Replace(";", ""))) { sendMainResult = MailHelper.SendMail(mail); } Response.Write(sendMainResult); }
發送郵件成功,附件也能正常打開,而且多個用戶都收到了電子郵件。截圖為證。
源代碼下載,請點擊這里。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。