ASP .NET Core 使用 MailKit 发送电子邮件

Gar*_*ary 3 asp.net-core-mvc mailkit

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("Username@hotmail.com", "Password");
                smtp.Send(message);
                smtp.Disconnect(true);
                return "Success";
            }
            catch (Exception ex)
            {
                return $"Failed. Error: {ex.Message}";
            }
        }
Run Code Online (Sandbox Code Playgroud)

使用 Gmail

smtp.Connect(
     "smtp.gmail.com"
   , 587
   , MailKit.Security.SecureSocketOptions.StartTls
);
Run Code Online (Sandbox Code Playgroud)

我尝试修改其他网站文章中的一些属性。

但是,我通常会收到以下错误消息:

  1. “失败。错误:SMTP 服务器不支持身份验证。”

  2. “失败。错误:根据验证程序,远程证书无效。”

如何正确设置属性?

Lin*_*yer 5

我在 ASP Core 中使用 MimeKit 发送到 Gmail。这是我的项目中对我有用的片段:

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);
}
Run Code Online (Sandbox Code Playgroud)