0

未使用 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();

任何帮助表示赞赏:) - 亲切的问候,

4

1 回答 1

2

您必须交换以下行。

client.Credentials = new NetworkCredential("<email>", "<password>");
client.UseDefaultCredentials = false;

您必须首先设置 UseDedaultCredentials 属性。

client.UseDefaultCredentials = false;    
client.Credentials = new NetworkCredential("<email>", "<password>");

就是这样,它应该工作。

于 2013-03-02T06:42:16.830 回答