使用带有smtp错误的gmail的ASP.NET:“连接尝试失败,因为连接方没有正确响应..”

时间:2017-02-22 12:54:52

标签: c# asp.net email model-view-controller smtp

我正在尝试向我的MVC网站添加新的电子邮件确认方法,因此每当用户注册时,他都会收到确认电子邮件。问题是,无论我使用什么代码(我在GitHub上找到了一些不同的选项),我总是得到同样的错误:

  

“连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应66.102.1.108:587”。

我使用的代码是:

using ATMProject.Models;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Security.Policy;
using System.Web;
using System.Web.Mvc;

namespace ATMProject.Services
{
    public class SendEmailConfirmation
    {
        public string email { get; set; }
        public string fullname { get; set; }
        public string username { get; set; }
        public string random { get; set; }

        public SendEmailConfirmation(string Email, string Fullname, 
          string Username, string Random) 
        {
            email = Email;
            fullname = Fullname;
            username = Username;
            random = Random;
        }

        public void sendEmail ()
        {
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new 
              System.Net.NetworkCredential("example@gmail.com", "123456");
            smtp.EnableSsl = true;
            MailMessage msg = new MailMessage();

            #region Msg
            msg.Subject = "Hello " + fullname;
            msg.Body = "Hello " + fullname + 
              "Thanks for Registering in Budgetize...Your Account Details are given below:";
            msg.Body += "<tr>";
            msg.Body += "<td>User Name :" + username + "</td>";
            msg.Body += "</tr>";
            msg.Body += "<tr>";
            msg.Body += "<td>Activation Number :" + random + "</td>";
            msg.Body += "</tr>";
            msg.Body += "<tr>";
            msg.Body += "<td>Thanking</td><td>Team Budgetize</td>";
            msg.Body += "</tr>";
            #endregion

            string toAddress = email; // Add Recepient address
            msg.To.Add(toAddress);
            string fromAddress = "\"Budgetize \" <example@example.com>";
            msg.From = new MailAddress(fromAddress);
            msg.IsBodyHtml = true;

            try {smtp.Send(msg);}
            catch (Exception ex) {throw;}
        }
    }
}

1 个答案:

答案 0 :(得分:1)

SMTP服务器需要安全连接,或者客户端未经过身份验证。服务器响应为:5.5.1需要身份验证。