使用csharp在aspdotnet中发送smtp邮件时出错

时间:2017-03-31 06:03:34

标签: c# asp.net smtp

我在下面分享了我的代码,在发送邮件时会抛出错误。



var fromAddress = new MailAddress("sender@gmail.com", "Customer");
        var toAddress = new MailAddress("reciever@gmail.com", "HR");
        const string fromPassword = "senderpass";
        const string subject = "Subject";
        const string body = "Body";

        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.EnableSsl = true;
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new NetworkCredential(fromAddress.Address, fromPassword);

        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body
        })
        {
            smtp.Send(message);
        }




这是更新的代码,但这也无效

1 个答案:

答案 0 :(得分:0)

尝试从Web配置配置主机,如下所示:

<system.net>
    <mailSettings>
      <smtp from="mail####hr@gmail.com">
        <network host="smtp.gmail.com" port="587" userName="mail####hr@gmail.com" password="##########"/>
      </smtp>
    </mailSettings>
  </system.net>

在您的类文件中更改方法如下,让我知道:

   string strMailBody ="test";
   string strToEmailId ="da###dotnet@gmail.com";
   string strSubject = "Mail Testing";
   SmtpClient Client = new SmtpClient();
   Client.EnableSsl = true;
   System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
    message.To.Add("mail####hr@gmail.com");
            message.Bcc.Add(strToEmailId);// (ToEmailId);
            message.Subject = strSubject;// "Subject";
            message.IsBodyHtml = true;
            message.Body = strMailBody;//Content;
            try
            {
                Client.Send(message);
            }
            catch (Exception ex)
            {

            }