最近在写一个邮件批量发送的小工具,用到了邮件的发送功能。其实现在这个在网上已经很多了,
现在我就把它提取出来做为一个独立的类,以后也方便使用。
using System; using System.Collections.Generic; using System.Text; using System.Net.Mail; using BatchEmail.Common.Item; using System.Configuration; namespace BatchEmail.Core { public class SendEmailHelper { private static int emailPort = Convert.ToInt32(ConfigurationSettings.AppSettings["EmailPort"]); private static string emailHost = ConfigurationSettings.AppSettings["EmailHost"]; public ResultResponse SendEmail(EmailObject emailObj) { ResultResponse response = new ResultResponse(); System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.From = new MailAddress(emailObj.Address, emailObj.DisplayName, System.Text.Encoding.UTF8); msg.To.Add(emailObj.EmailTo); msg.Subject = emailObj.Subject;//邮件标题 msg.SubjectEncoding = System.Text.Encoding.UTF8;//邮件标题编码 msg.Body =emailObj.EmailBody;//邮件内容 msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件 msg.IsBodyHtml = true; msg.Priority = MailPriority.Normal; SmtpClient client = new SmtpClient(); client.Credentials = new System.Net.NetworkCredential(emailObj.UserName, emailObj.Password); client.Port = emailPort;//使用的端口 client.Host = emailHost; //client.EnableSsl = true;//经过ssl加密 object userState = msg; //client.Send(msg); try { //client.SendAsync(msg, userState); //client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted); client.Send(msg); response.State = true; response.Msg = "Send Email Success!"; } catch (System.Net.Mail.SmtpException ex) { response.State = false; response.Msg = ex.Message; } return response; } //void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) //{ // // frm.UpdateProcessBar(); //} } }
其中EmailObject 是数据实体类
using System; using System.Collections.Generic; using System.Text; namespace BatchEmail.Common.Item { public class EmailObject { public string Address { get; set; } public string DisplayName { get; set; } public string EmailTo { get; set; } public string Subject { get; set; } public string EmailBody { get; set; } public string UserName { get; set; } public string Password { get; set; } } }
其中要注意的就是,一般个人使用gmail的挺多的,端口是587,host 是smtp.gmail.com,且一定要设置client.EnableSsl = true;
另外如果是公司的邮箱发,如果host是exchange的话,端口也要用587而不是25.
一般企业的邮箱发送都不需要lient.EnableSsl = true;所以这行可以识具体情况添加。如果提识没有相应的证书且就把
lient.EnableSsl = true去掉即可。当然发送邮件是采用同步还是异步的方式就看项目要求了,如果采用同步发送,主UI界面会阻塞,所以
最好是另外开一个线程来发邮件。邮件状态可以通过委托来实现邮件发送状态的显示。