简体   繁体   English

通过gmail使用SMTP发送电子邮件

[英]Send Email using SMTP via gmail

I'm working in ASP.Net Core and trying to send email using smtp client from gmail. 我正在ASP.Net Core中工作,并尝试使用Gmail的smtp客户端发送电子邮件。 Have following code but it's not working Have seen following post as well but it doesn't work http://dotnetthoughts.net/how-to-send-emails-from-aspnet-core/ 有以下代码,但不起作用也有看过以下帖子,但不起作用http://dotnetthoughts.net/how-to-send-emails-from-aspnet-core/

It thorws following error 错误后鸣叫

System.NotSupportedException: The SMTP server does not support authentication System.NotSupportedException:SMTP服务器不支持身份验证

var emailMessage = new MimeMessage();
emailMessage.From.Add(new MailboxAddress("From Name", "fromEmail@gmail.com"));
emailMessage.To.Add(new MailboxAddress("To Name", "toEmail@gmail.com"));
emailMessage.Subject = subject;

var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = message;
emailMessage.Body = bodyBuilder.ToMessageBody();

var client = new SmtpClient();
try
{
    await client.ConnectAsync("smtp.gmail.com", 25, SecureSocketOptions.None).ConfigureAwait(false);
    client.AuthenticationMechanisms.Remove("XOAUTH2");  
    await client.AuthenticateAsync("fromEmail@gmail.com", "fromPassword"); //error occurs here

    await client.SendAsync(emailMessage).ConfigureAwait(false);
    await client.DisconnectAsync(true);
    await client.DisconnectAsync(true).ConfigureAwait(false);
}
catch(Exception e)
{

}

The NotSupportedException is thrown because GMail does not support authentication without using an SSL/TLS connection because it only supports non-encrypted password-based authentication mechanisms. 抛出NotSupportedException是因为GMail仅支持基于密码的非加密身份验证机制,因此不使用SSL / TLS连接就不支持身份验证。

I would recommend connecting like this: 我建议这样连接:

client.ConnectAsync("smtp.gmail.com", 587, SecureSocketOptions.StartTls)

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM