项目中需要对异常,发送邮件到管理员邮箱
发送时候会卡死一段时间
如何发送呢?
1、首先在QQ邮箱当中开启“POP3/SMTP服务”
这里有个东西需要开启,拿到授权码,而不是用qq密码明文的方式展示出来
温馨提醒:为了你的帐户安全,更改QQ密码以及独立密码会触发授权码过期,需要重新获取新的授权码登录。
https://service.mail.qq.com/cgi-bin/help?subtype=1&&no=1001256&&id=28
手机发送“配置邮箱客户端”,之后就可以弹出这个授权码页面
这里说的一般的腾讯邮箱指的的是@qq.com这样的邮箱,在程序里需要配置如下:
SMTP服务器: ssl://smtp.qq.com
端口:465或587
用户名和密码:自己的邮箱号和密码
本文来源于:牛超个人博客(大超小志)
原文标题: 解决腾讯企业邮箱smtp.exmail.qq.com发邮件错误
原文链接:http://niuchao.com/technology/668
实现代码:
发送人,收件人,都是一样的
//发件人地址 MailAddress from = new MailAddress("824478152@qq.com"); MailMessage message = new MailMessage(); message.Body = "this is a test"; message.IsBodyHtml = true; message.BodyEncoding = System.Text.Encoding.UTF8; //收件人地址 message.To.Add("824478152@qq.com"); message.Subject = "hello !"; message.SubjectEncoding = System.Text.Encoding.UTF8; message.From = from; SmtpClient client = new SmtpClient(); client.EnableSsl = true; client.Host = "smtp.qq.com"; client.Port = 587; //邮箱账户和密码 client.Credentials = new System.Net.NetworkCredential("824478152@qq.com", "授权码"); try { client.Send(message); } catch (Exception ex) { string mssage = ex.ToString(); }
程序中的抛异常发邮件过程
之前发送异常会卡死程序很久,以为是数据库回滚的问题,排查下来是,邮件提醒功能,发送失败造成的
Service服务中throw;
BLL中throw,弹出异常
HandlerErrorAttribute--
public override void OnException(ExceptionContext context)-----》WriteLog(context);
private void WriteLog(ExceptionContext context)----》SendMail(string body)
private void SendMail(string body)-----》Config.GetValue("ErrorToMail").ToBool()----true--》MailHelper.Send("824478152@qq.com", SystemName + " - 发生异常", body.Replace("-", ""));
public class MailHelper
public static bool Send(string to, string subject, string body, string encoding = "UTF-8", bool isBodyHtml = true, bool enableSsl = false)
/// <summary> /// 同步发送邮件 /// </summary> /// <param name="to">收件人邮箱地址</param> /// <param name="subject">主题</param> /// <param name="body">内容</param> /// <param name="encoding">编码</param> /// <param name="isBodyHtml">是否Html</param> /// <param name="enableSsl">是否SSL加密连接</param> /// <returns>是否成功</returns> public static bool Send(string to, string subject, string body, string encoding = "UTF-8", bool isBodyHtml = true, bool enableSsl = false) { try { MailMessage message = new MailMessage(); // 接收人邮箱地址 message.To.Add(new MailAddress(to)); message.From = new MailAddress(MailUserName, MailName); message.BodyEncoding = Encoding.GetEncoding(encoding); message.Body = body; //GB2312 message.SubjectEncoding = Encoding.GetEncoding(encoding); message.Subject = subject; message.IsBodyHtml = isBodyHtml; SmtpClient smtpclient = new SmtpClient(MailServer, 587); smtpclient.Credentials = new System.Net.NetworkCredential(MailUserName, MailPassword); //SSL连接 smtpclient.EnableSsl = enableSsl; smtpclient.Send(message); return true; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return false; } }