如何使用Gmail的SMTP客户端在C#中向自己发送电子邮件而不启用Gmail设置中安全性较低的应用的访问权限?

时间:2014-08-07 14:33:52

标签: c# asp.net email gmail



我正在使用asp.net网络表单应用程序,并且我尝试以编程方式向自己发送电子邮件。我使用的是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);
    }
}

2 个答案:

答案 0 :(得分:0)

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);

答案 1 :(得分:0)

有可能在没有“允许安全性较低的应用程序”的情况下使用Google SMTP服务器。选项,但您无法使用标准的Google用户名和密码。请参阅我在其他帖子上的说明:

Is there a way to use ASP.NET to send email through a Google Apps acccount without selecting the 'Allow less secure apps' option?