1

我正在尝试使用 C# mvc 发送一封基本电子邮件...由于某种原因它不起作用..我尝试了许多不同的解决方案,但在浏览器中不断收到相同的错误,显示“操作已超时”..我认为是连接问题。错误开始于“client.Send(mail); 我在我的本地机器上执行此操作。我尝试使用端口 587,465,995,25,但没有运气。在 Visual Studio 的编译器中,当我构建它时,我没有收到任何错误。我只需在网络浏览器中在线获取错误“client.Send(mail);”

控制器:

  public void SendEmail(History hi)
  {
    SmtpClient client = new SmtpClient();   //server type
    client.Port = 587;                      
    client.Host = "smtp.gmail.com";         //google
    client.EnableSsl = true;                //SSl set to true
    client.Timeout = 10000;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Credentials = new System.Net.NetworkCredential("papasmurf985@gmail.com", "******"); 

    MailMessage mail = new MailMessage("papasmurf985@gmail.com", "papasmurf985@gmail.com", "Test Score", "Your score is" + hi.score);
    mail.BodyEncoding = System.Text.Encoding.UTF8;
    mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

    client.Send(mail);                      
  }

网络配置:

<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network">
      <network host="smtp.gmail.com" port="587" />
    </smtp>
  </mailSettings>
</system.net>

我也在 web.config 中试过这个:

<system.net>
   <mailSettings>
     <smtp from="no-reply@no-reply.com">
       <network host="smtp.gmail.com" port="587" enableSsl="true"
                userName="papasmurf985@gmail.com" password="PASSWORD" />
     </smtp>
   </mailSettings>
</system.net>
4

2 回答 2

1

请尝试以下方法

public void SendMessage(string toAddress, string subjectText, string bodyText)
{
    //create a object to hold the message
    MailMessage newMessage = new MailMessage();

    //Create addresses
    MailAddress senderAddress = new MailAddress(your_gmail_address);
    MailAddress recipentAddress = new MailAddress(toAddress);

    //Now create the full message
    newMessage.To.Add(recipentAddress);
    newMessage.From = senderAddress;
    newMessage.Subject = subjectText;
    newMessage.Body = bodyText;

    //Create the SMTP Client object, which do the actual sending
    SmtpClient client = new SmtpClient(your_gmail_server_address, your_gmail_port)
    {
        Credentials = new NetworkCredential(your_gmail_address, your_password),
        EnableSsl = true
    };


    //now send the message
    client.Send(newMessage);
}

这段代码对我有用

于 2013-03-11T13:09:36.130 回答
0

我首先要确保您的 ISP 不会阻止外部 SMTP 服务器

于 2013-03-11T07:51:07.330 回答