我尝试编写用于发送带有.NET的电子邮件的代码。这就是我到目前为止所做的:
MailMessage mail = new MailMessage("mymailaddress@yahoo.com", address);
mail.Subject = subject;
mail.Body = body;
client.Host = "smtp.gmail.com";
client.Port = 587;
client.Send(e);
问题是我得到以下异常:
未处理的例外:
System.Net.Mail.SmtpException
:发送邮件失败。
System.Net.WebException
:无法连接到远程服务器。
System.Net.Sockets.SocketException
:连接尝试因连接方失败而失败 一段时间后未正确响应,或已建立的连接失败,因为已连接的主机未能响应173.194.66.109:587
答案 0 :(得分:2)
试试这个:
using System.Net;
using System.Net.Mail;
// ...
MailAddress maFrom = new MailAddress("<address>", "<display_name>");
MailAddress maTo = new MailAddress("<address>", "<display_name>");
const string sPassword = "<password>";
const string sSubject = "<subject>";
const string sBody = "<body>";
new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(maFrom.Address, sPassword)
}.Send(new MailMessage(maFrom, maTo) { Subject = sSubject, Body = sBody });