ASP .NET Core using MailKit to send e-mail

7.5k views Asked by At
public static string Send(string to, string subject, string content, string from = "")
        {
            try
            {
                MimeMessage message = new MimeMessage();
                message.Subject = subject;
                message.Body = new TextPart("Plain") { Text = content };
                message.From.Add(new MailboxAddress(from));
                message.To.Add(new MailboxAddress(to));

                SmtpClient smtp = new SmtpClient();
                smtp.Connect(
                      "smtp.live.com"
                    , 587
                    , MailKit.Security.SecureSocketOptions.StartTls
                );
                smtp.Authenticate("[email protected]", "Password");
                smtp.Send(message);
                smtp.Disconnect(true);
                return "Success";
            }
            catch (Exception ex)
            {
                return $"Failed. Error: {ex.Message}";
            }
        }

using gmail

smtp.Connect(
     "smtp.gmail.com"
   , 587
   , MailKit.Security.SecureSocketOptions.StartTls
);

I tried modify some properties that from other website's articles.

But, I usually get these error messages:

  1. "Failed. Error: The SMTP server does not support authentication."

  2. "Failed. Error: The remote certificate is invalid according to the validation procedure."

How to set the properties correctly?

1

There are 1 answers

0
Lin Meyer On BEST ANSWER

I use MimeKit in ASP Core to send to Gmail. Here is a snippet from my project that works for me:

using (var client = new SmtpClient())
{
 client.Connect(_appSettings.SmtpServerAddress, _appSettings.SmtpServerPort, SecureSocketOptions.StartTlsWhenAvailable);
 client.AuthenticationMechanisms.Remove("XOAUTH2"); // Must be removed for Gmail SMTP
 client.Authenticate(_appSettings.SmtpServerUser, _appSettings.SmtpServerPass);
 client.Send(Email);
 client.Disconnect(true);
}