ASP .NET Core 使用 MailKit 发送邮件
ASP .NET Core using MailKit to send e-mail
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}";
}
}
使用 Gmail
smtp.Connect(
"smtp.gmail.com"
, 587
, MailKit.Security.SecureSocketOptions.StartTls
);
我尝试修改了其他网站文章中的一些属性。
但是,我通常会收到这些错误消息:
"Failed. Error: The SMTP server does not support authentication."
”失败。错误:远程证书无效
验证程序。"
如何正确设置属性?
我在 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);
}
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}";
}
}
使用 Gmail
smtp.Connect(
"smtp.gmail.com"
, 587
, MailKit.Security.SecureSocketOptions.StartTls
);
我尝试修改了其他网站文章中的一些属性。
但是,我通常会收到这些错误消息:
"Failed. Error: The SMTP server does not support authentication."
”失败。错误:远程证书无效 验证程序。"
如何正确设置属性?
我在 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);
}