使用ASP.NET MVC C从gmail SMTP发送电子邮件#

时间:2015-12-16 16:19:03

标签: c# asp.net-mvc-4 smtp gmail

我正在创建应用并返回错误。这是web.config文件中配置SMTP连接的一部分:

<system.net>
    <mailSettings>
      <smtp>
        <network host="smtp.gmail.com" 
                 port="587" 
                 userName="mymail@gmail.com" 
                 password="mypassword" 
                 enableSsl="true"
                 defaultCredentials="false"/>
      </smtp>
    </mailSettings>
  </system.net>

以下是Helpers控制器中的代码:

namespace Subscription.Helpers
{
    public static class MailHelper
    {
        private static SmtpClient _smtpClient;

        static MailHelper()
        {
            _smtpClient = new SmtpClient();
        }

        public static void SendEmail(List<string> recipientAddress, string subject, string news)
        {
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress("mymail@gmail.com", "Google.com", Encoding.UTF8);

                foreach(string address in recipientAddress)
                {
                    mail.Bcc.Add(new MailAddress(address));
                }

                mail.Subject = subject;
                mail.Body = news;
                mail.SubjectEncoding = Encoding.UTF8;
                mail.BodyEncoding = Encoding.UTF8;
                mail.Priority = MailPriority.High;

                _smtpClient.Send(mail);
            }
        }
    }
}

当我想向数据库中的所有地址发送电子邮件时,它会返回未处理的异常并进行通信:&#34;未指定SMTP主机&#34;和line&#34; _smtpClient.Send(mail);&#34;在源错误。我做错了什么?

1 个答案:

答案 0 :(得分:0)

首先在您的代码中添加说明,如下所示:

<smtp deliveryMethod="Network" from="username@gmail.com">

然后在你的代码后面添加smtp.EnableSsl = true;并从web.config中删除它。