3
我有一些旧的代码可以很好地发送电子邮件,但visual studio告诉我代码已经过时,我应该从Web.Mail
更改为Net.Mail
。我重写了大部分内容,但我有几个问题。System.Net.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
,即导致它超时?
谢谢!
SOLUTION
由于DavidH的方向是正确的点,端口需要从改为(或25;我使用的是前者没有问题)。
一定没有使用正确的搜索字词......我发誓我没发布前!谢谢。 – Anders
所有的好,只是很高兴有一个剪切干燥修复。 :) – Haney