扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
发送电子邮件也是项目开发当中经常用到的功能,这里我整理了一个发送电子邮件(带附件,支持多用户发送,主送、抄送)的类库,供大家参考。
创新互联建站"三网合一"的企业建站思路。企业可建设拥有电脑版、微信版、手机版的企业网站。实现跨屏营销,产品发布一步更新,电脑网络+移动网络一网打尽,满足企业的营销需求!创新互联建站具备承接各种类型的做网站、网站制作项目的能力。经过十载的努力的开拓,为不同行业的企事业单位提供了优质的服务,并获得了客户的一致好评。先上两个实体类,用于封装成Mail对象。
////// 发送邮件请求 /// public class MailRequest { #region PrivateFields ////// 文件名 /// private string _fromField; ////// 返送到 /// private string _toField; ////// 抄送 /// private string _copyField; ////// 附件 /// private string _bccField; ////// 标题 /// private string _subjectField; ////// 发送人名 /// private string _bodyField; ////// 类容 /// private MailRequestAttachments[] _p_w_uploadsField; #endregion ////// 发送人,多个人以分号;间隔 /// public string From { get { return this._fromField; } set { this._fromField = value; } } ////// 收件人,多个人以分号;间隔 /// public string To { get { return this._toField; } set { this._toField = value; } } ////// 抄送人,多个人以分号;间隔 /// public string CC { get { return this._copyField; } set { this._copyField = value; } } ////// 秘密抄送人,多个人以分号;间隔 /// public string Bcc { get { return this._bccField; } set { this._bccField = value; } } ////// 主题 /// public string Subject { get { return this._subjectField; } set { this._subjectField = value; } } ////// 内容 /// public string Body { get { return this._bodyField; } set { this._bodyField = value; } } ////// 附件列表 /// public MailRequestAttachments[] Attachments { get { return this._p_w_uploadsField; } set { this._p_w_uploadsField = value; } } }
////// 发送邮件请求附件 /// public class MailRequestAttachments { #region PrivateFields ////// 文件名 /// private string _fileNameField; ////// 文件内容 /// private byte[] _fileDataField; #endregion ////// 文件名 /// public string FileName { get { return this._fileNameField; } set { this._fileNameField = value; } } ////// 文件内容 /// public byte[] FileData { get { return this._fileDataField; } set { this._fileDataField = value; } } }
附件的内容很简单,因为在网络传输当中,是以字节流的形式传输的,因此附件的传输需要转换成字节流数组。
////// 邮件帮助类 /// public static class MailHelper { ////// 发送邮件 /// /// 邮件内容对象 ///发送邮件所遇到的异常 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; } } ////// 解析分解邮件地址 /// /// 邮件地址 /// 邮件对象 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)); } } ////// 字节数组转换为流 /// /// 字节数组 ///Stream private static Stream ByteArrayToStream(byte[] byteArray) { MemoryStream mstream = new MemoryStream(byteArray); return mstream; } }
这是一个邮件助手类,定义成static,无需实例化,直接类名.方法名的形式调用。
只需要上述3个类就可以实现发送Email了,由于上面引用的是web.config里面的信息(asp.net等命名空间,如果是winform等需要自己修改一下),这里还需要配置一下web.config,如下所示:
最后上一个测试方法,在主函数当中或者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.欢迎访问我的博客。";//内容 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); }
发送邮件成功,附件也能正常打开,而且多个用户都收到了电子邮件。截图为证。
源代码下载,请点击这里。
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流