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);
}

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

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);
}

如果您想知道,我在代码_port_smtp设置了更高的值,分别为 465 和 smtp.gmail.com。

所以它似乎有效,但随后进入发送部分并吐出其中之一:

System.Net.Mail.SmtpException: The operation has timed out.

有没有我遗漏的东西,比如Fields原始代码中的,导致它超时?

谢谢!

解决方案

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

4

1 回答 1

6

一点谷歌可以走很长的路。检查此答案以解决您的问题-您使用了错误的端口:

https://stackoverflow.com/a/11244548/2420979

于 2013-07-22T17:15:49.757 回答