首页 > 代码库 > .NET MVC之邮件发送

.NET MVC之邮件发送

在以前的项目中,设计到发送邮件的WEB站,当时在网上找了一段代码研究了一下:

    private static void SendEmail(string clientHost, string emailAddress, string receiveAddress,
          string userName, string password, string subject, string body)
        {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(emailAddress);
            mail.To.Add(new MailAddress(receiveAddress));
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = true;
            mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

            SmtpClient client = new SmtpClient();
            client.Host = clientHost;
            client.Credentials = new NetworkCredential(userName, password);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            try
            {
                client.SendAsync(mail,null);
            }
            catch (Exception)
            {

            }
        }

  在本地测试没问题,但是部署到window server2012上就无法发送了,然后在网上百度了一堆,配置邮件服务器什么的都不尽人意,后来发现一种已弃用的代码反而正常了:

  public static void SendEmail(string from, string subject, string body, List<string> mailAddress, string host, int port, string password)
        {
            System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
            try
            {

                mail.To = string.Join(",", mailAddress);

                mail.From = from;
                mail.Subject = subject;
                mail.BodyFormat = System.Web.Mail.MailFormat.Html;
                mail.Body = body;

                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //身份验证
                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", mail.From); //邮箱登录账号,这里跟前面的发送账号一样就行
                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", password); //这个密码要注意:如果是一般账号,要用授权码;企业账号用登录密码
                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 465);//端口
                mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");//SSL加密
                System.Web.Mail.SmtpMail.SmtpServer = "smtp.qq.com";    //企业账号用smtp.exmail.qq.com
                System.Web.Mail.SmtpMail.Send(mail);

                //邮件发送成功
            }
            catch (Exception ex)
            {
                //失败,错误信息:ex.Message;
            }
        }

  技术分享

后来发现可能是因为服务器架设在内网中,特定端口没开或者一些限制,不过由于工作要求,暂时只能退步走了,以后一定要改正过来。

 

.NET MVC之邮件发送