无法使用sendgrid(C#)发送电子邮件,也无法查看例外情况

时间:2017-03-06 06:52:48

标签: c# email sendgrid

我在代码中使用SendAsync方法来触发电子邮件。电子邮件代码打印在下面。

public async Task SendAsync(IdentityMessage message) {
 if (message.Destination != null)
  await configSendGridasync(message);
}
private async Task configSendGridasync(IdentityMessage message) {
 var myMessage = new SendGridMessage();
 myMessage.AddTo(message.Destination);
 myMessage.From = new MailAddress(ConfigurationManager.AppSettings["mailAccount"], "XYC Social");
 myMessage.Subject = message.Subject;
 myMessage.Text = message.Body;
 myMessage.Html = message.Body;

 var credentials = new NetworkCredential(
  ConfigurationManager.AppSettings["mailAccount"],
  ConfigurationManager.AppSettings["mailPassword"]
 );

 // Create a Web transport for sending email.
 var transportWeb = new Web(credentials);

 // Send the email.
 if (transportWeb != null) {
  await transportWeb.DeliverAsync(myMessage);
 } else {
  Trace.TraceError("Failed to create Web transport.");
  await Task.FromResult(0);
 }
}

在控制器中,我使用下面的代码来触发电子邮件。

public async Task < ActionResult > ForgotPassword(XYCSocial.Models.ManageUserViewModel model) {
 IdentityMessage msg = new IdentityMessage {
  " Message",
  Subject = "Reset Password",
  Destination = result.Email
 };
 try {
  await _emailService.SendAsync(msg);
 } catch (Exception ex) {
  ViewBag.Status = "Error : " + ex.Message;
  throw;
 }

 TempData["Success"] = " Some Message";
 return RedirectToAction("Login");
}
} else {
 TempData["Failed"] = "Please enter valid User name";
 return RedirectToAction("Login");
}
} catch (Exception) {


 TempData["Failed"] = "Email Send Failed..Please Try After Some Time";
 return RedirectToAction("Login");

然而,当我在控制器中调用SendAsync方法来触发电子邮件时,它只会执行而不会出现错误,但电子邮件永远不会被发送。

经过很长一段时间后,它说:

  

电子邮件发送失败

来自上面的TempData["Failed"]标记。我已经验证了sendgrid帐户中的suppressions文件夹,但没有垃圾邮件,电子邮件地址或阻止等信号。

这段相同的代码工作到2017年2月17日,但之后就没有工作。

1 个答案:

答案 0 :(得分:1)

我也使用类似的代码遇到了同样的问题。我今晚发现的是sendgrid GitHub页面https://github.com/sendgrid/sendgrid-csharp

上的更新样本

这是针对V3版本的Sendgrid Mail。

我可以确认将此代码与Azure托管的MVC 5解决方案一起使用:

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 = "Hello World from the SendGrid CSharp SDK!";
        var to = new EmailAddress("test@example.com", "Example User");
        var plainTextContent = "Hello, Email!";
        var htmlContent = "<strong>Hello, Email!</strong>";
        var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
        var response = await client.SendEmailAsync(msg);

您需要替换整个Config方法并在Azure门户管理器中添加环境变量(您需要从Sendgrid站点获取)