添加类 SendEmailHelper
public static class SendEmailHelper
{
private static MailMessage mailMessage;
private static SmtpClient smtpClient;
private static string password;
public static void Init(string To, string Title, string Body)
{
string From = ConfigurationManager.AppSettings["EmailSource"].ToString();
string Password = ConfigurationManager.AppSettings["EmailPwd"].ToString();
SendMail(To, From, Body, Title, Password);
Send();
}
public static void SendMail(string To, string From, string Body, string Title, string Password)
{
try
{
mailMessage = new MailMessage();
mailMessage.To.Add(To);
mailMessage.From = new System.Net.Mail.MailAddress(From);
mailMessage.Subject = Title;
mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;
mailMessage.Body = Body;
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
mailMessage.Priority = System.Net.Mail.MailPriority.Normal;
password = Password;
}
catch (Exception ex)
{
throw new Exception("初始化邮件错误!" + ex.Message);
}
}
public static void Attachments(string Path)
{
try
{
string[] path = Path.Split(',');
Attachment data;
ContentDisposition disposition;
for (int i = 0; i < path.Length; i++)
{
data = new Attachment(path[i], MediaTypeNames.Application.Octet);
disposition = data.ContentDisposition;
mailMessage.Attachments.Add(data);
}
}
catch (Exception ex)
{
throw new Exception("添加附件错误!" + ex.Message);
}
}
public static void SendAsync(SendCompletedEventHandler CompletedMethod)
{
if (mailMessage != null)
{
smtpClient = new SmtpClient();
smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, password);
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Host = "smtp." + mailMessage.From.Host;
smtpClient.SendCompleted += new SendCompletedEventHandler(CompletedMethod);
smtpClient.SendAsync(mailMessage, mailMessage.Body);
}
}
public static void Send()
{
try
{
if (mailMessage != null)
{
smtpClient = new SmtpClient();
smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, password);
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Host = "smtp." + mailMessage.From.Host;
smtpClient.Send(mailMessage);
}
}
catch (Exception ex)
{
throw new Exception("发送错误!" + ex.ToString());
}
}
}
调用