使用MailHelper发送SendGrid电子邮件

时间:2016-09-07 23:39:00

标签: c# email sendgrid

我正在使用SendGrid mailhelper(作为C#SDK的一部分)来发送电子邮件。我需要发送给多个用户,因此我使用Personalization。

我收到错误:错误请求

这是我的代码:

 static async Task Execute(string sub, string body, List<Recipient> recipients)
    {
        string apiKey = Environment.GetEnvironmentVariable("SendGrid_ApiKey", EnvironmentVariableTarget.User);

        dynamic sg = new SendGridAPIClient(apiKey);

        SendGrid.Helpers.Mail.Email from = new SendGrid.Helpers.Mail.Email("test1@gmail.com");
        string subject = sub;
        Personalization personalization = new Personalization();

       SendGrid.Helpers.Mail.Email emails = new SendGrid.Helpers.Mail.Email();
        var i = 0;
        foreach (var recp in recipients)
        {
            emails.Address = recp.Email;
            emails.Name = recp.FirstName + " " + recp.LastName;
            personalization.AddTo(emails);
            i++;
        }
        SendGrid.Helpers.Mail.Email to = new SendGrid.Helpers.Mail.Email("test1@gmail.com");

        Content content = new Content("text/plain", body);
        Mail mail = new Mail(from, subject, to, content);
        mail.AddPersonalization(personalization);
        dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
    }

如果有人能告诉我我做错了什么,我感激不尽。

1 个答案:

答案 0 :(得分:1)

当Personalization对象中有多个电子邮件地址相同时,Sendgrid API会响应错误请求。确保所有电子邮件都是唯一的