我有一些老的代码可以发送电子邮件,但是Visual Studio告诉我这个代码过时了,建议我将它改为Net.Mail
而不再使用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;我正在使用前者没有问题)。