在MVC中使用SendGrid发送邮件

时间:2019-05-12 20:07:05

标签: c# asp.net-mvc sendgrid

我正在使用SendGrid发送确认邮件以确认电子邮件,但是 ApiKey始终为空

public Task SendAsync(IdentityMessage message)
{

    var ApiKey = Environment.GetEnvironmentVariable("ApiKeyFromSendGrid");
    var client = new SendGridClient(ApiKey);
    var from = new EmailAddress("XXX@gmail.com", "Any Name");
    var subject = "Sending with SendGrid is Fun";
    var to = new EmailAddress(message.Destination, "Any Name");
    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 = client.SendEmailAsync(msg);

    return response;

}

错误在哪里? enter image description here

2 个答案:

答案 0 :(得分:0)

错误在于恢复环境变量:

Environment.GetEnvironmentVariable("ApiKeyFromSendGrid");

ApiKeyFromSendGrid存在吗?

看看这些问题和答案是否可以帮助您正确检索环境变量:

How do I get and set Environment variables in C#?

Environment.GetEnvironmentVariable won't find variable value

答案 1 :(得分:0)

您为API密钥使用了错误的值。您正在使用API​​密钥ID。如果您没有将原始密钥值存储在某个地方,则可能需要创建一个新密钥。

请参见SendGrid API Key not working. "The provided authorization grant is invalid, expired or revoked"