.net 邮件报警

需求上要求在website出现错误的时候能将提醒到相应的人员,于是尝试用公司使用的邮件组件来做。然做好后,却不能正常发送邮件,于是自己用MS的邮件功能做了个简单的邮件发送,测试可行。

 

目标框架:.net framework 4.6.1

 

以下为mvc模式下的Global.asax中error处理方法,若使用.net core请参考https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/error-handling?view=aspnetcore-6.0错误处理。

        void Application_Error(object sender, EventArgs e)
        {
            Exception exc = Server.GetLastError();

            SmtpClient smtpClient = new SmtpClient("stc.c.COM");//邮件服务器
            string toMail = System.Configuration.ConfigurationManager.AppSettings["EmailTo"];//收件人邮箱
            string mailCc = System.Configuration.ConfigurationManager.AppSettings["EmailCc"];//抄送人邮箱

            MailAddress mailFrom = new MailAddress("VM@c.com","VM", System.Text.Encoding.UTF8);//发送人邮箱
            MailAddress mailTo = new MailAddress(toMail);
            MailMessage mailMessage = new MailMessage(mailFrom,mailTo);

            mailMessage.CC.Add(new MailAddress(mailCc));
            mailMessage.Body = $@"
                                                      From:{Environment.MachineName}
                                                      Error:{exc.Message}      
                                                      Please troubleshooting or do something. ";
            mailMessage.Subject = "Visual Test";
            mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;

            smtpClient.Send(mailMessage);
        }
SmtpClient 详细使用参考链接:MSDN

注意上述的邮件发送,使用异步的时候需要处理一下(详细见其报错提示)。

 

 

以上记之以备忘。

posted @ 2022-02-09 14:49  盛沧海  阅读(52)  评论(0编辑  收藏  举报