我想使用我的应用程序发送电子邮件。
我试过这个:
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(form);
mail.To.Add(to);
mail.Subject = subject;
mail.Body = body;
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
smtp.Credentials = new NetworkCredential(form, password);
smtp.EnableSsl = true;
smtp.Send(mail);
}
}
但是当我发送邮件时,他告诉我“SMTP 服务器需要安全连接,或者客户端未经过身份验证。服务器响应是:5.7.0 需要身份验证。”
如何解决这个问题?
您可以使用以下代码通过gmail smtp客户端发送电子邮件:
string body = "your-email-body-here";
try
{
using (var smtpClient = new SmtpClient("smtp.gmail.com", 587)) // default port is usually 587 in gmail
{
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential()
{
UserName = Config.Username, // your Gmail username
Password = Config.Password, // your Gmail password
};
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
smtpClient.Send("[email protected]", "[email protected]", "Account verification", body);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}