简体   繁体   English

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

[英]Sending e-mail from gmail SMTP with ASP.NET MVC C#

I'm creating app and it return error. 我正在创建应用程序,它返回错误。 This is part of configuration SMTP connection in web.config file: 这是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>

And below is code in Helpers controller: 下面是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);
            }
        }
    }
}

When I want to send email to all addresses from database it return unhandled exception with communicate: "The SMTP host was not specified" and line "_smtpClient.Send(mail);" 当我想将电子邮件发送到数据库中的所有地址时,它会返回未处理的异常并进行通信:“未指定SMTP主机”和“ _smtpClient.Send(mail);”行 in source error. 源错误。 What I'm doing wrong? 我做错了什么?

First add descriptions to your tag like this: 首先,向标签添加描述,如下所示:

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

Then in your code behind add smtp.EnableSsl = true; 然后在您的代码后面添加smtp.EnableSsl = true; and remove it from you web.config. 并将其从您的web.config中删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM