System.Net.Mail发送超时

And*_*ers 3 c# system.net.mail system.web.mail asp.net-mvc-4

我有一些较旧的代码可以很好地发送电子邮件,但是Visual Studio告诉我该代码已过时,我应该将其更改为Net.Mailfrom Web.Mail。我已经重写了大部分内容,但是我有几个问题。

这是原始的工作代码:

public void Send(string from, string to, string subject, string body, bool isHtml, string[] attachments)
{

    var mailMessage = new MailMessage

    {
        From = from,
        To = to,
        Subject = subject,
        Body = body,
        BodyFormat = isHtml ? MailFormat.Html : MailFormat.Text
    };


    // Add attachments
    if (attachments != null)
    {
        foreach (var t in attachments)
        {
            mailMessage.Attachments.Add(new Attachment(t));
        }
    }
    mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
    mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _accountName);
    mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _password);
    mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _port.ToString(CultureInfo.InvariantCulture)); 
    mailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", true);

    SmtpMail.SmtpServer = _smtp;
    SmtpMail.Send(mailMessage);
}
Run Code Online (Sandbox Code Playgroud)

这是重写的部分(嗯,有点):

public void Send2(string from, string to, string subject, string body, bool isHtml, string[] attachments)
{
var fromObj = new MailAddress(from);
var toObj = new MailAddress(to);


var mailMessage = new System.Net.Mail.MailMessage
                      {
                          From = fromObj,
                          Subject = subject,
                          Body = body,
                          IsBodyHtml = isHtml,
                      };

mailMessage.To.Add(toObj);

if (attachments != null)
{
    foreach(var t in attachments)
    {
        mailMessage.Attachments.Add(new Attachment(t));
    }
}

var smtp = new SmtpClient(_smtp) {Credentials = new NetworkCredential(_accountName, _password), Port = _port, EnableSsl = true};
smtp.Send(mailMessage);
}
Run Code Online (Sandbox Code Playgroud)

如果你想知道,我_port_smtp分别在代码中设置了较高的465和smtp.gmail.com。

因此它似乎可以正常工作,但随后进入发送部分并吐出其中之一:

System.Net.Mail.SmtpException: The operation has timed out.
Run Code Online (Sandbox Code Playgroud)

我是否缺少某些东西(例如Fields原始代码中的)导致其超时?

谢谢!

由于DavidH的方向正确,因此端口需要从465更改为587(或25;我使用前者没有问题)。

Han*_*ney 5

一个小小的Google可以走很长一段路。检查此答案是否可以治愈-您使用的端口错误:

/sf/answers/787118391/

  • 一定没有使用正确的搜索词...我保证我确实在发布前看过!谢谢。 (2认同)