public static string fromEmail = "123123123@qq.com";//邮件发送方
public static string fromPwd = "xxxxxxxxxxxxx"; //邮件发送方密码/QQ授权码
public static string emailType = "smtp.qq.com";//邮件类型 smtp.163.com.cn; smtp.qq.com.cn; smtp.126.com.cn; smtp.sina.com.cn
/// <summary>
/// 发送电子邮件
/// </summary>
/// <param name="toEmail">接收方电子邮件</param>
/// <param name="subject">邮件标题</param>
/// <param name="body">邮件内空</param>
/// <param name="attFile">附件</param>
public static void SendEmail(string toEmail, string subject, string body, string attFile)
{
MailAddress addrFrom = new MailAddress(fromEmail, fromEmail);
MailAddress addrTo = new MailAddress(toEmail, toEmail);
MailMessage mm = new MailMessage(addrFrom, addrTo);
mm.BodyEncoding = Encoding.UTF8;
mm.IsBodyHtml = true;
mm.Subject = subject;
mm.Body = body;
//文件缺失存在
if (!string.IsNullOrEmpty(attFile) && File.Exists(attFile))
{
Attachment att = new Attachment(attFile, MediaTypeNames.Application.Octet);
ContentDisposition cd = att.ContentDisposition;
cd.CreationDate = File.GetCreationTime(attFile);
cd.ModificationDate = File.GetLastWriteTime(attFile);
cd.ReadDate = File.GetLastAccessTime(attFile);
mm.Attachments.Add(att);//添加附件
}
NetworkCredential nc = new NetworkCredential(fromEmail, fromPwd);
SmtpClient smtp = new SmtpClient(emailType);
smtp.EnableSsl = true; //启用SSl
//随请求一起发送
smtp.UseDefaultCredentials = false;
//邮件账户凭证
smtp.Credentials = nc;
//邮件发送方式-网络发送
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
//服务器证书验证回调
ServicePointManager.ServerCertificateValidationCallback = delegate (Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
try
{
smtp.Send(mm);
}
catch (SmtpFailedRecipientException)
{
smtp.Dispose();
return;
}
catch (Exception ex)
{
throw ex;
}
smtp.Dispose();
}
邮件发送
最新推荐文章于 2024-05-27 21:44:11 发布