使用gmail smtp设置不会从C#代码发送电子邮件。它给出了错误“服务器需要安全连接或客户端未经过身份验证。”
电子邮件和密码与登录时使用的相同..
以下是完整的代码。
MailMessage mail = new MailMessage("<from>","<to>");
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.Credentials = new NetworkCredential("<email>", "<password>");
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Timeout = 20000;
client.UseDefaultCredentials = false;
mail.Body = "Test email from C# Code";
mail.Subject = "Test Email";
Console.WriteLine("Attempting to Send Email");
try {
client.Send(mail);
Console.WriteLine("Email sent... ");
}
catch (System.Net.Mail.SmtpFailedRecipientException ex) {
Console.WriteLine("Could not send email to the mentioned recipient" + ex.Message);
}
catch (System.Net.Mail.SmtpException ex) {
Console.WriteLine("Could not send Email..\n" + ex.Message + "\n" + ex.StackTrace);
}
Console.ReadLine();
任何帮助表示赞赏:) - 亲切的问候,
答案 0 :(得分:2)
您必须交换以下行。
client.Credentials = new NetworkCredential("<email>", "<password>");
client.UseDefaultCredentials = false;
您必须首先设置UseDedaultCredentials属性。
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("<email>", "<password>");
就是这样,它应该有效。