【发布时间】:2019-08-18 11:16:10
【问题描述】:
我将 sendgrid 设置为使用 web api(而不是 smtp 中继)来发送电子邮件。 我按照 C# 如何发送电子邮件的说明进行操作,包括创建 api 密钥环境变量和安装 nuget 包 sendgrid。
调用 client.SendEmailAsync(msg) 后返回的响应是“Accepted”,表示一切正常。但是我的测试邮件没有收到邮件。
关闭 Windows Defender 防火墙后,已发送电子邮件。所以我认为防火墙阻止了我的电子邮件发送?
我的问题是,如何在防火墙中为 sendgrid 添加例外设置以允许从 sendgrid 发出电子邮件,或者我错过了 sendgrid 或防火墙中的配置?
代码:
var apiKey = Environment.GetEnvironmentVariable("SendGridApiKey");
var client = new SendGridClient(apiKey);
var from = new EmailAddress("test@example.com", "Example User");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress("my_outlook_email_here", "Example User");
var plainTextContent = "and easy to do anywhere, even with C#";
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
我将端口 25 和 587 添加到 TCP 和 UDP 的入站规则和出站规则中,以在 windows 防火墙中打开端口,但仍然无法发送电子邮件。
【问题讨论】:
-
允许你的 smtp 端口 25 和 587。它会工作。
-
SMTP 是一种 HTTP 类型,它具有必须编码的特殊字符(请参阅:en.wikipedia.org/wiki/…)。电子邮件可能失败,因为您没有对特殊字符进行编码。您可以使用 System.Net.WebUtility.HtmlEncode(string) 进行编码。你能解释一下你的电子邮件包含什么吗?任何附件以及您使用的模式。
-
我在上面更新了我的代码以包含电子邮件的内容
-
@jdweng SMTP 不是 HTTP 类型。它与 HTTP 无关。 SMTP 早在 HTTP 之前就发明了。