【发布时间】:2020-01-23 12:18:39
【问题描述】:
我必须使用 sendgrid 发送一封替换邮件。 我使用以下代码:
public async Task SendConfirmationMailAsync(UserCreateViewModel model, string domain, ApplicationUser user)
{
string q = _encryption.EncryptText(model.Email + "|" + model.Password, _configuration["Security:EncryptionKey"]);
string encryptdetexturl = HttpUtility.UrlEncode(q);
string url = domain + "/Device/RegisterDevice?q=" + encryptdetexturl;
Dictionary<string, string> substitution = new Dictionary<string, string>();
substitution.Add("-indirizzo_email-", url);
await _emailService.SendEmailAsync(user.Email, "d-1201e63adfa04976ba9fc17212172fe9", substitution);
}
调用
public async Task SendEmailAsync(ApplicationUser applicationUser, string templateId)
{
var apiKey = _configuration["Email:apikey"];
var client = new SendGridClient(apiKey);
var from = new EmailAddress(_configuration["Email:Email"]);
var to = new EmailAddress(applicationUser.Email);
var substitutions = GetReplacement(applicationUser);
var msg = MailHelper.CreateSingleTemplateEmail(from, to, templateId, null,substitutions);
var response = await client.SendEmailAsync(msg);
Trace.WriteLine(msg.Serialize());
Trace.WriteLine(response.StatusCode);
Trace.WriteLine(response.Headers);
}
调用
public static SendGridMessage CreateSingleTemplateEmail(
EmailAddress from,
EmailAddress to,
string templateId,
object dynamicTemplateData,
Dictionary<string, string> substitutions)
{
if (string.IsNullOrWhiteSpace(templateId))
{
throw new ArgumentException($"{nameof(templateId)} is required when creating a dynamic template email.", nameof(templateId));
}
var msg = new SendGridMessage();
msg.SetFrom(from);
msg.AddTo(to);
msg.TemplateId = templateId;
if (dynamicTemplateData != null)
{
msg.SetTemplateData(dynamicTemplateData);
}
if (substitutions != null)
{
msg.AddSubstitutions(substitutions);
}
return msg;
}
发送过程总是失败可能是因为在第三种方法中我分离了 dynamicTemplateData 和替换。我必须发送一条引用存储在 sendgrid 中的模板的消息,并且我没有将其传递给方法。
Sendgrid 错误如下:
{"发件人":{"email":"info@elettrone.com"},"个性化":[{"to":[{"email":"yocax2@elettrone.com"}],"替换":{"-indirizzo_email-":"https://localhost:44391/Device/RegisterDevice?q=tnGdfw1EojMggP15KY39IWJGE9GkYWOTzMBsungIHrNJm6gzwc1r1zRpMZDH55%2fQ"}}],"template_id":"d-1201e63adfa04976ba9fc17212172fe9"} 错误的请求 服务器:nginx 日期:2019 年 9 月 23 日星期一 18:06:50 GMT 连接:保持活动 访问控制允许来源:https://sendgrid.api-docs.io 访问控制允许方法:POST Access-Control-Allow-Headers:授权、Content-Type、代表、x-sg-elas-acl 访问控制最大年龄:600 X-No-CORS-原因:https://sendgrid.com/docs/Classroom/Basics/API/cors.html
谁能帮帮我?
【问题讨论】:
-
您得到的实际异常是什么?
-
@silleknarf : 我收到 SendGrid BadRequest 异常。
-
@mason 这不是 .NET 异常,而是我从 SendGrid 响应中得出的异常。
-
@mason:这是一个 SendGrid BadRequest 失败消息。它不会发送电子邮件,但程序不会崩溃。
-
@mason :我将其添加到帖子中。