asp.net发送E-mail
发送电子邮件也是项目开发当中经常用到的功能,这里我整理了一个发送电子邮件(带附件,支持多用户发送,主送、抄送)的类库,供大家参考。
成都创新互联公司主营什邡网站建设的网络公司,主营网站建设方案,app软件开发,什邡h5成都微信小程序搭建,什邡网站营销推广欢迎什邡等地区企业咨询
先上两个实体类,用于封装成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); }
发送邮件成功,附件也能正常打开,而且多个用户都收到了电子邮件。截图为证。
源代码下载,请点击这里。
新闻标题:asp.net发送E-mail
文章位置:http://pwwzsj.com/article/pssdhi.html