邮件帮组类
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Mail; using System.Net.Mime; using System.Text; using System.Threading; using System.Threading.Tasks; namespace LionTech.Utility.MELMRP { public class MailSender { private String _EmailSMTPServer = String.Empty; //SMTP位置 private int _EmailSMTPPort = 25; //SMTP Port private mailAddr _sender = new mailAddr("", ""); private String _Subject = String.Empty;//信件標題 private String _Content = String.Empty;//信件內容 private List_ReplayTo = new List ();//信件回覆位置 private List _Receiver = new List ();//信件接收者 private List _CC = new List ();//副本 private List _BCC = new List ();//密件副本 private Boolean _EnableSSL = false;//是否啟用SSL private Boolean _EnableTHML = true;//是否為HTML內容 private Boolean _Notification = false;//信件回函 private List _AttachmentFiles = new List ();//附件 private Encoding _SubjectEncoding = Encoding.UTF8;//標題編碼 private Encoding _ContentEncoding = Encoding.UTF8;//內容編碼 private MailPriority _Priority = MailPriority.Normal;//優先順序 /// 設定、取得信件寄件者 public mailAddr sender { get { return _sender; } set { _sender = value; } } ///設定、取得信件標題 public String Subject { get { return _Subject; } set { //_Subject = value; _Subject = String.Format("=?UTF-8?B?{0}?=", Convert.ToBase64String(Encoding.UTF8.GetBytes(value))); } } ///設定、取得信件內容 public String Content { get { return _Content; } set { _Content = value; } } ///設定、取得信件回覆位置 public ListReplayTo { get { return _ReplayTo; } set { _ReplayTo = value; } } /// 設定、取得信件接收者 public ListReceiver { get { return _Receiver; } set { _Receiver = value; } } /// 設定、取得信件副本 public ListCC { get { return _CC; } set { _CC = value; } } /// 設定、取得信件密件副本 public ListBCC { get { return _BCC; } set { _BCC = value; } } /// 設定、取得是否啟用SSL(def:false) public bool EnableSSL { get { return _EnableSSL; } set { _EnableSSL = value; } } ///設定、取得是否為HTML內容(def:true) public bool EnableTHML { get { return _EnableTHML; } set { _EnableTHML = value; } } ///設定、取得是否需要信件回函(def:false) public bool Notification { get { return _Notification; } set { _Notification = value; } } ///設定、取得信件附件 public ListAttachmentFiles { get { return _AttachmentFiles; } set { _AttachmentFiles = value; } } /// 設定、取得信件標題編碼 public Encoding Encoding_Subject { get { return _SubjectEncoding; } set { _SubjectEncoding = value; } } ///設定、取得信件內容編碼 public Encoding Encoding_Content { get { return _ContentEncoding; } set { _ContentEncoding = value; } } ///設定、取得信件優先順序 public MailPriority Priority { get { return _Priority; } set { _Priority = value; } } ///設定、取得發送郵件的 thread *非同步發信新增 public Thread SendThread { get; set; } ///建構子 /// SMTP位置 /// SMTP Port (通常為 25) public MailSender(String SMTPServer, int SMTPPort) { _EmailSMTPServer = SMTPServer; _EmailSMTPPort = SMTPPort; } ///建構子 (default port:25) /// public MailSender(String SMTPServer) : this(SMTPServer, 25) { } public MailSender() { } #region 非同步發信新增的程式區段 ---------------------------------------------- ///非同步發信函數。 public void BeginSend() { SendThread = new Thread(new ThreadStart(BeginSendSubThread)); SendThread.Name = "MailSendThread"; SendThread.Start(); } private void BeginSendSubThread() { try { Send(); } catch { } SendThread.Abort(); //結束非同步發信的執行緒 } #endregion -------------------------------------------------------------------- ///信件發送函數。 public bool Send() { MailMessage mail = new MailMessage(); mail.From = new MailAddress(sender.mail, sender.name);//寄件者 mail.IsBodyHtml = EnableTHML; //信件本文是否為HTML mail.Body = Content; //設定本文內容 mail.BodyEncoding = _ContentEncoding; mail.Subject = Subject; //設定信件標題 mail.SubjectEncoding = _ContentEncoding; //mail.Priority = MailPriority.High; if (Receiver.Count > 0)//收件者 Parallel.ForEach(Receiver, (item, loopState) => { if (IsValidEmail(item.mail)) mail.To.Add(new MailAddress(item.mail, item.name)); }); if (ReplayTo.Count > 0)//設定信件回覆位置 Parallel.ForEach(ReplayTo, (item, loopState) => { if (IsValidEmail(item.mail)) mail.ReplyToList.Add(new MailAddress(item.mail, item.name)); }); if (CC.Count > 0)//加入信件副本 Parallel.ForEach(CC, (item, loopState) => { if (IsValidEmail(item.mail)) mail.CC.Add(new MailAddress(item.mail, item.name)); }); if (BCC.Count > 0)//加入信件密件副本 Parallel.ForEach(BCC, (item, loopState) => { if (IsValidEmail(item.mail)) mail.Bcc.Add(new MailAddress(item.mail, item.name)); }); if (Notification && IsValidEmail(sender.mail))//回條 mail.Headers.Add("Disposition-Notification-To", sender.mail); if (AttachmentFiles.Count > 0) { Parallel.ForEach(AttachmentFiles, (item, loopState) => { if (item != null && item.FileStream != null && item.FileStream.Length > 0 && !String.IsNullOrWhiteSpace(item.FileName)) mail.Attachments.Add(new Attachment(item.FileStream, item.FileName)); }); } mail.Priority = _Priority;//優先順序 try { //如果是空的,取 webconfig 中設定值 if (string.IsNullOrWhiteSpace(_EmailSMTPServer)) { using (SmtpClient SC = new SmtpClient()) { SC.Send(mail); } } else { SmtpClient SC = new SmtpClient(_EmailSMTPServer, _EmailSMTPPort); SC.EnableSsl = EnableSSL; //是否開啟SSL SC.Host = _EmailSMTPServer; SC.Port = _EmailSMTPPort; SC.UseDefaultCredentials = true; //设置邮箱发送服务 SC.Credentials = new NetworkCredential("3781100649@163.com", "13055673352zzz"); SC.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; SC.Send(mail); //發送 return true; } } catch (Exception ex) { return false; } return false; } public static bool IsValidEmail(string strIn) { if (!String.IsNullOrWhiteSpace(strIn)) { // Return true if strIn is in valid e-mail format. return System.Text.RegularExpressions.Regex.IsMatch(strIn, @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$"); } else return false; } } public class mailAddr { private String _name = String.Empty; private String _mail = String.Empty; private String _encodeName = string.Empty; public String name { get { return _name; } } public String mail { get { return _mail; } } public String encodeName { get { return _encodeName; } } public mailAddr(String name, String email) { _name = name; _mail = email; _encodeName = !string.IsNullOrWhiteSpace(name) ? String.Format("=?UTF-8?Q?{0}?=", Uri.EscapeDataString(name).Replace("%", "=")) : ""; } } public class AttachmentFile { private Stream _fStream; private String _fName = String.Empty; public Stream FileStream { get { return _fStream; } } public String FileName { get { return _fName; } } public AttachmentFile(Stream FileStream, String FileName) { _fStream = FileStream; _fName = FileName; } } }
发送邮件
//获取文件流 FileStream fileStream = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); //获取文件名 string FileName = "Web.config"; byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, bytes.Length); Stream stream = new MemoryStream(bytes); stream.Flush(); fileStream.Close(); //设置邮件信息 MailSender sendEmail = new MailSender("smtp.163.com", 25) { //发件人 sender = new mailAddr("发送人名称", "邮箱地址"), //收件人 Receiver = new List() { new mailAddr("张伟东", Buffer_Addresseeemail) }, //主旨 Subject = Query_title, //内容 Content = Query_content, //发送附件 AttachmentFiles = new List () { new AttachmentFile(stream, FileName) } }; //发送邮件 if (sendEmail.Send()) { //发送邮件成功! stream.Close(); return true; } else { //发送邮件失败! stream.Close(); return false; }
进一步操作,封装邮件发送方法,可通过网络发送和发送到本地硬盘中
#region 發送Email到本地 ////// 發送Email到本地 /// /// 發送者Email地址 /// 接收者Email地址 /// 標題 /// 內容 /// 本地存放絕對路徑 public void sendEmailToLocation(string senderEmail, ListtoEmail, string subject, string content, string locationPath) { MailMessage email = new MailMessage(); email.From = new MailAddress(senderEmail); foreach (mailAddr addr in toEmail) { if (string.IsNullOrWhiteSpace(addr.mail)) continue; email.To.Add(new MailAddress(addr.mail)); } email.IsBodyHtml = true; email.Body = content; email.Subject = subject; SmtpClient stmp = new SmtpClient(Account.EmailSmtp, Account.EmailSmtpPort); stmp.UseDefaultCredentials = true; stmp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; //发送的路径 stmp.PickupDirectoryLocation = locationPath; stmp.Send(email); } #endregion #region 發送網絡郵件 /// /// 發送網絡郵件 /// /// 發送者發送郵件名稱 /// 發送者郵箱地址 /// 接受者 /// 主題 /// 內容 public void sendEmailToNetWork(string senderName, string senderEmail, ListtoEmail, string subject, string content) { //邮件发送类 MailSender sendEmail = new MailSender(Account.EmailSmtp, Account.EmailSmtpPort); //发送者 sendEmail.sender = new mailAddr(senderName, Account.mailSenderMail); //接收者 foreach (mailAddr addr in toEmail) { if (string.IsNullOrWhiteSpace(addr.mail)) continue; sendEmail.Receiver.Add(new mailAddr(addr.name, addr.mail)); } //主题 sendEmail.Subject = subject; //内容 sendEmail.Content = content; sendEmail.EnableTHML = true; //发送邮件 sendEmail.BeginSend(); } #endregion
详细解释
public static void sendmail_2(){SmtpClient smtp = new SmtpClient(); //实例化一个SmtpClientsmtp.DeliveryMethod = SmtpDeliveryMethod.Network; //将smtp的出站方式设为 Networksmtp.EnableSsl = false;//smtp服务器是否启用SSL加密smtp.Host = "smtp.163.com"; //指定 smtp 服务器地址smtp.Port = 25; //指定 smtp 服务器的端口,默认是25,如果采用默认端口,可省去//如果你的SMTP服务器不需要身份认证,则使用下面的方式,不过,目前基本没有不需要认证的了smtp.UseDefaultCredentials = true; //如果需要认证,则用下面的方式smtp.Credentials = new NetworkCredential("a@163.com", "****");MailMessage mm = new MailMessage(); //实例化一个邮件类mm.Priority = MailPriority.High; //邮件的优先级,分为 Low, Normal, High,通常用 Normal即可mm.From = new MailAddress("b@163.com", "真有意思测试", Encoding.GetEncoding(936));//收件方看到的邮件来源;//第一个参数是发信人邮件地址//第二参数是发信人显示的名称//第三个参数是 第二个参数所使用的编码,如果指定不正确,则对方收到后显示乱码 //936是简体中文的codepage值//注:上面的邮件来源,一定要和你登录邮箱的帐号一致,否则会认证失败mm.ReplyTo = new MailAddress("b@163.com", "我的接收邮箱", Encoding.GetEncoding(936));//ReplyTo 表示对方回复邮件时默认的接收地址,即:你用一个邮箱发信,但却用另一个来收信//上面后两个参数的意义, 同 From 的意义//mm.CC.Add("a@163.com,b@163.com,c@163.com");//邮件的抄送者,支持群发,多个邮件地址之间用 半角逗号 分开//当然也可以用全地址,如下:mm.CC.Add(new MailAddress("c@163.com", "抄送者A", Encoding.GetEncoding(936)));//mm.CC.Add(new MailAddress("b@163.com", "抄送者B", Encoding.GetEncoding(936)));//mm.CC.Add(new MailAddress("c@163.com", "抄送者C", Encoding.GetEncoding(936)));//mm.Bcc.Add("d@163.com,e@163.com");//邮件的密送者,支持群发,多个邮件地址之间用 半角逗号 分开//当然也可以用全地址,如下://mm.CC.Add(new MailAddress("d@163.com", "密送者D", Encoding.GetEncoding(936)));//mm.CC.Add(new MailAddress("e@163.com", "密送者E", Encoding.GetEncoding(936)));//mm.Sender = new MailAddress("xxx@xxx.com", "邮件发送者", Encoding.GetEncoding(936));//可以任意设置,此信息包含在邮件头中,但并不会验证有效性,也不会显示给收件人//说实话,我不知道有啥实际作用,大家可不理会,也可不写此项//mm.To.Add("g@163.com,h@163.com");//邮件的接收者,支持群发,多个地址之间用 半角逗号 分开//当然也可以用全地址添加mm.To.Add(new MailAddress("g@163.com", "接收者g", Encoding.GetEncoding(936)));//mm.To.Add(new MailAddress("h@163.com", "接收者h", Encoding.GetEncoding(936)));mm.Subject = "这是邮件标题-测试"; //邮件标题mm.SubjectEncoding = Encoding.GetEncoding(936); // 这里非常重要,如果你的邮件标题包含中文,这里一定要指定,否则对方收到的极有可能是乱码。// 936是简体中文的pagecode,如果是英文标题,这句可以忽略不用mm.IsBodyHtml = true; //邮件正文是否是HTML格式mm.BodyEncoding = Encoding.GetEncoding(936); //邮件正文的编码, 设置不正确, 接收者会收到乱码mm.Body = "邮件测试,呵呵"; //邮件正文mm.Attachments.Add(new Attachment(@"c:\d\1.doc", System.Net.Mime.MediaTypeNames.Application.Rtf)); //添加附件,第二个参数,表示附件的文件类型,可以不用指定//可以添加多个附件//mm.Attachments.Add(new Attachment(@"d:b.doc"));smtp.Send(mm); //发送邮件,如果不返回异常, 则大功告成了。}