【发布时间】:2016-05-26 03:16:49
【问题描述】:
我正在尝试发送一封带有 C# 代码的电子邮件,从 MSDN 上的示例复制而来(例如 https://msdn.microsoft.com/en-us/library/14k9fb7t%28v=vs.110%29.aspx)
// from and password contain my credentials
// to contains a valid email address
public static void CodeExample()
{
try
{
using (MailMessage mail = new MailMessage(from, to))
{
using (SmtpClient server = new SmtpClient("smtp.googlemail.com"))
{
mail.From = new MailAddress(from);
mail.To.Add(new MailAddress(to));
mail.Subject = "Test subject";
mail.Body = "Test message";
mail.IsBodyHtml = false;
server.Port = 465;
server.Credentials = new System.Net.NetworkCredential(from, password);
server.UseDefaultCredentials = true;
server.EnableSsl = true;
server.ServicePoint.MaxIdleTime = 1;
server.Timeout = 60000;
Console.WriteLine("Sending to {0} by using SMTP host {1} port {2}.", to.ToString(), server.Host, server.Port);
server.Send(mail);
Console.WriteLine("mail Sent");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("Inner Exception:");
Console.WriteLine(ex.InnerException?.ToString());
}
}
但我总是遇到异常:
System.Net.Mail.SmtpException:发送邮件失败。 ---> System.IO.IOException: 无法从传输连接读取数据:net_io_connectionclosed。
“发件人”地址的详细信息已经过检查,看起来没问题。从 Yahoo! 发送帐户以同样的方式失败。我尝试了很多不同的SmtpClient 属性组合。我的防火墙日志中没有消息。
使用 Thunderbird,我可以从 Googlemail 和 Yahoo! 发送邮件帐户没有问题。
我将不胜感激有关如何使其工作的任何提示。
编辑
我看过这个帖子SmtpException: Unable to read data from the transport connection: net_io_connectionclosed
Google 邮件在端口 587 上失败(使用和注释掉 UseDefaultCredentials = true 和 EnableSsl = true),报告我有一个不安全的应用程序。我会试试雅虎!稍后在 587 端口上。
【问题讨论】:
-
SmtpClient server- 我喜欢这种命名约定;p -
使用 smtp 客户端为
new SmtpClient("smtp.gmail.com")并为服务器端口分配值587