[英]How do I to use MailMessage to send mail using SendGrid?
我正在尝试使用 SendGrid 发送邮件,但我不能。 它总是抛出一个我无法修复的异常。
我该如何解决这个问题?
发邮件
public static Boolean isSend(IList<String> emailTo, String mensagem, String assunto, String emailFrom, String emailFromName){
try{
MailMessage mail = new MailMessage();
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
//to
foreach (String e in emailTo) {
mail.To.Add(e);
}
mail.From = new MailAddress(emailFrom);
mail.Subject = assunto;
mail.Body = mensagem;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = CustomEmail.SENDGRID_SMTP_SERVER;
smtp.Port = CustomEmail.SENDGRID_PORT_587;
smtp.Credentials = new System.Net.NetworkCredential(CustomEmail.SENDGRID_API_KEY_USERNAME, CustomEmail.SENDGRID_API_KEY_PASSWORD);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = false;
smtp.Timeout = 20000;
smtp.Send(mail);
return true;
}catch (SmtpException e){
Debug.WriteLine(e.Message);
return false;
}
}
自定义邮件
//SendGrid Configs
public const String SENDGRID_SMTP_SERVER = "smtp.sendgrid.net";
public const int SENDGRID_PORT_587 = 587;
public const String SENDGRID_API_KEY_USERNAME = "apikey"; //myself
public const String SENDGRID_API_KEY_PASSWORD = "SG.xx-xxxxxxxxxxxxxxxxxxxxxxxxx-E";
例外
Exception thrown: 'System.Net.Mail.SmtpException' in System.dll
Server Answer: Unauthenticated senders not allowed
对于使用 SendGrid 发送电子邮件,有v3 API 。 NuGet 名称是 SendGrid,链接在这里。
该库不适用于System.Net.Mail.MailMessage
,它使用SendGrid.Helpers.Mail.SendGridMessage
。
该库使用 API 密钥进行授权。 You can create one when you log into SendGrid web app, and navigate to Email API -> Integration Guide -> Web API -> C#.
var client = new SendGridClient(apiKey);
var msg = MailHelper.CreateSingleTemplateEmail(from, new EmailAddress(to), templateId, dynamicTemplateData);
try
{
var response = client.SendEmailAsync(msg).Result;
if (response.StatusCode != HttpStatusCode.OK
&& response.StatusCode != HttpStatusCode.Accepted)
{
var errorMessage = response.Body.ReadAsStringAsync().Result;
throw new Exception($"Failed to send mail to {to}, status code {response.StatusCode}, {errorMessage}");
}
}
catch (WebException exc)
{
throw new WebException(new StreamReader(exc.Response.GetResponseStream()).ReadToEnd(), exc);
}
我认为您的问题源于没有在构造函数中使用服务器实例化 SMTP 客户端。 此外,您应该将 smtpclient 包装在 using 语句中,以便正确处理它,或者在完成后调用 dispose。
尝试这个:
public static Boolean isSend(IList<String> emailTo, String mensagem, String assunto, String emailFrom, String emailFromName)
{
try
{
MailMessage mail = new MailMessage();
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
//to
foreach (String e in emailTo)
{
mail.To.Add(e);
}
mail.From = new MailAddress(emailFrom);
mail.Subject = assunto;
mail.Body = mensagem;
mail.IsBodyHtml = true;
using(SmtpClient smtp = new SmtpClient(CustomEmail.SENDGRID_SMTP_SERVER)){
smtp.Port = CustomEmail.SENDGRID_PORT_587;
smtp.Credentials = new System.Net.NetworkCredential(CustomEmail.SENDGRID_API_KEY_USERNAME, CustomEmail.SENDGRID_API_KEY_PASSWORD);
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = false;
smtp.Timeout = 20000;
smtp.Send(mail)
}
}
catch (SmtpException e)
{
Debug.WriteLine(e.Message);
return false;
}
}
如果这不起作用,您可以尝试删除 smtp 客户端的端口、 enablesl 和 usedefaultcredentials 参数。 我一直使用 sendgrid 并且不使用这些选项。
为了更具体地回答您的原始问题和异常原因,SendGrid SMTP 服务器可能不是在寻找您帐户的用户名和密码,而是在寻找您的 API 密钥。 该错误似乎表明您的身份验证不成功。
https://sendgrid.com/docs/for-developers/sending-email/v3-csharp-code-example/
要与 SendGrids SMTP API 集成:
- 创建至少具有“邮件”权限的 API 密钥。
- 将 email 客户端或应用程序中的服务器主机设置为 smtp.sendgrid.net。
- 此设置有时称为外部 SMTP 服务器或 SMTP 继电器。
- 将您的用户名设置为 apikey。
- 将您的密码设置为在步骤 1 中生成的 API 密钥。
- 将端口设置为 587。
使用 SendGrid C# 库也将简化此过程:
https://sendgrid.com/docs/for-developers/sending-email/v3-csharp-code-example/
// using SendGrid's C# Library
// https://github.com/sendgrid/sendgrid-csharp
using SendGrid;
using SendGrid.Helpers.Mail;
using System;
using System.Threading.Tasks;
namespace Example
{
internal class Example
{
private static void Main()
{
Execute().Wait();
}
static async Task Execute()
{
var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.