微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么有时无法使用Azure SendGrid从ASP.Net核心Web应用程序发送我的电子邮件,

如何解决为什么有时无法使用Azure SendGrid从ASP.Net核心Web应用程序发送我的电子邮件,

我正在使用Azure Sendgrid从我的ASP.net核心Web应用程序发送电子邮件。间歇地,某些收件人没有收到电子邮件。有些收件人会收到电子邮件,而其他收件人则不会。

为简洁起见,下面的代码包括设置MailMessage(FROM,TO等...)

我将“ smtp.sendgrid.net”用作smtpserver,将“端口” 587用作smtpport。

string smtpServer = ConfigurationManager.AppSettings["MailSMTPServer"];
   int smtpPort = int.Parse(ConfigurationManager.AppSettings["MailPort"]);
   string username = ConfigurationManager.AppSettings["MailUserName"];
   string pwd = ConfigurationManager.AppSettings["MailPassword"];


   SmtpClient client = new SmtpClient(smtpServer);

   client.Port = smtpPort;
   client.UseDefaultCredentials = false;
   client.Credentials = new NetworkCredential(username,pwd);
   client.DeliveryMethod = SmtpDeliveryMethod.Network;

   client.Send(mailMessage);

我已经与IT部门进行了交谈,那里没有收到电子邮件,以查看是否被阻止。没有电子邮件到达其服务器的记录。

解决方法

recommended是通过SMTP使用其REST API

  • SMTP中继会创建多个潜在故障点,这意味着发送方与 SendGrid可能导致这些“不正常”消息之一。
  • Web API更快。 SMTP中继中多余的来回传递可能会导致外来客户的某些(最小)延迟 美国,因此离我们的入站数据中心更远。
  • Web API还允许您通过使用API keys为程序添加额外的安全性。 API密钥可让您生成一个 身份验证凭据与您的用户名密码分开, 大大降低了有人使用您的帐户发送邮件的机会 垃圾邮件或网络钓鱼。

此外,由于outbound SMTP restriction in Azure,可能存在白名单问题。如果改用REST API,则可以克服这一点。

这里是一个C# example,使用其nuget

var apiKey = "<send grid api key>";
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("test@example.com","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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。