我有一些较旧的代码适用于发送电子邮件,但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;我正在使用前者没有问题)。
答案 0 :(得分:3)
一个小小的谷歌走了很长的路。检查这个答案你的治疗方法 - 你使用了错误的端口: