我如何使用Gmail的SMTP客户端在c#中发送电子邮件给我自己,而不启用Gmail设置中不太安全的应用程序的访问?

本文关键字:Gmail 设置 不启用 安全 访问 应用程序 我自己 电子邮件 客户端 SMTP 何使用 | 更新日期: 2023-09-27 18:17:01

我正在做一个ASP。. NET Web表单应用程序,我试图以编程方式发送电子邮件给自己。我正在使用Gmail的SMTP客户端,一切都很好,除了当我发送邮件时,我得到了这个错误:

"System.Net.Mail。SmtpException: SMTP服务器要求安全连接或客户端未经过身份验证。服务器响应为:5.5.1认证要求。了解更多

如果我进入我的gmail帐户设置并启用一个允许我访问"不太安全的应用程序"的选项,一切都很好。我想知道如何在启用此选项的情况下发送电子邮件。

protected void sendEmail(object sender, EventArgs e)
{
    var client = new SmtpClient("smtp.gmail.com", 587)
    {
        Credentials = new System.Net.NetworkCredential("myusername@gmail.com", "mypassword"),
        DeliveryMethod = SmtpDeliveryMethod.Network,
        EnableSsl = true
    };
    
    MailAddress from = new MailAddress("myusername@gmail.com", "Torchedmuffinz");
    MailAddress to = new MailAddress("myusername@gmail.com", "Torchedmuffinz");
    MailMessage message = new MailMessage(from, to);
    message.Subject = "test";
    message.Body = "test";
    Attachment attachFile = new Attachment(@"pathtofile");
    message.Attachments.Add(attachFile);
    try { client.Send(message); }
    catch (Exception email_exception)
    {
        System.Diagnostics.Debug.WriteLine(email_exception);
    }
}

我如何使用Gmail的SMTP客户端在c#中发送电子邮件给我自己,而不启用Gmail设置中不太安全的应用程序的访问?

Gmail端口587不支持SSL。

我认为下面的代码应该为你工作。

MailMessage msg = new MailMessage();
msg.From=new MailAddress("yourmail@gmail.com");
msg.To.Add("receiver@receiverdomain.com");
msg.Subject="Your Subject";
msg.Body="Message content is going to be here";
msg.IsBodyHtml=false; //if you are going to send an html content, you have to make this true
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port=587;
NetworkCredential credential=new NetworkCredential("yourmail@gmail.com","your gmail password");
client.UseDefaultCredentials=false;
client.Credentials=credential;
client.Send(msg);

有可能使用谷歌SMTP服务器没有'允许不太安全的应用程序'选项,但你不能使用你的标准谷歌用户名和密码。参见我在其他帖子上的说明:

是否有办法使用ASP。NET通过谷歌应用程序帐户发送电子邮件而不选择"允许不太安全的应用程序"选项?