简体   繁体   中英

Send Email using SMTP via gmail

I'm working in ASP.Net Core and trying to send email using smtp client from gmail. 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/

It thorws following error

System.NotSupportedException: The SMTP server does not support authentication

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.

I would recommend connecting like this:

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

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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