我有 Asp.net core Web 应用程序并使用 Mailkit 发送电子邮件:
emailMessage.From.Add(new MailboxAddress("John", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9c3c6c1c7e9c6dcddc5c6c6c287cac6c4" rel="noreferrer noopener nofollow">[email protected]</a>"));
emailMessage.To.Add(new MailboxAddress("Doe", email));
emailMessage.Subject = subject;
emailMessage.Body = new TextPart("plain") { Text = message };
using (var client = new SmtpClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("smtp-mail.outlook.com", 587, false);
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate("<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c565354527c53494850535357125f5351" rel="noreferrer noopener nofollow">[email protected]</a>", "password");
client.Send(emailMessage);
client.Disconnect(true);
}
在 VS 上本地运行应用程序时,它发送得很好。但是,当我在发送电子邮件时将其上传到 Azure 应用服务时,它失败并显示以下消息:
SmtpProtocolException: The SMTP server has unexpectedly disconnected.
MailKit.Net.Smtp.SmtpStream.ReadAhead(CancellationToken cancellationToken)
MailKit.Net.Smtp.SmtpStream.ReadResponse(CancellationToken cancellationToken)
MailKit.Net.Smtp.SmtpClient.SendCommand(string command, CancellationToken cancellationToken)
MailKit.Net.Smtp.SmtpClient.Authenticate(Encoding encoding, ICredentials credentials, CancellationToken cancellationToken)
MailKit.MailService.Authenticate(string userName, string password, CancellationToken cancellationToken)
有人知道怎么解决吗?
最佳答案
Microsoft Azure 不允许端口 25 上的出站连接,并且还会阻止所有出站 SMTP,除非连接到第三方 SMTP 提供商 SendGrid,该提供商是 Microsoft Azure 唯一“受祝福的”出站电子邮件提供商。
(我认为这很奇怪,因为你可能会认为 Microsoft 想要在 Azure 中展示他们的 Exchange 服务,并与 AWS 的电子邮件服务竞争)
SendGrid 每月最多可免费发送 20,000 封电子邮件(幸运的是 - 否则这将是敲诈勒索),之后仍然相当便宜。
您可以直接从 Azure 门户中创建 SendGrid 帐户,然后单击“管理”按钮打开您的 SendGrid 帐户详细信息并获取其 SMTP 详细信息,包括用户名和密码。
SendGrid 提供两个 API:第一个只是原始的“哑”SMTP 服务,尽管默认情况下它们会将您的电子邮件延迟 10 分钟(以减少垃圾邮件),直到您的帐户被视为“可信”。他们的第二个 API 是您可以使用的 HTTP Web 服务 - 这对于重负载场景更好,因为 HTTP 连接比 SMTP 连接便宜。
关于Asp.net core 邮件包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42895082/