sendgrid多个收件人c#

时间:2016-08-02 16:33:02

标签: c# email sendgrid

我正在使用此代码从Web应用程序发送电子邮件。只有一个收件人没问题。我研究过使用来自https://sendgrid.com/docs/Integrate/Code_Examples/v3_Mail/csharp.html的相同技术向多个收件人发送电子邮件。我尝试用逗号分隔的字符串作为destinatario(参见代码中的args),即“you@example.com,she @ example.com,he @ example.com”,但SendGrid只接受第一个收件人。我也尝试使用数组,但结果是simmilar,SG只接受最后一个收件人。传递收件人列表的正确方法是什么?

eval

}

4 个答案:

答案 0 :(得分:1)

您的问题的答案可以在库的source代码中找到,有两个构造函数可以创建Mail对象。您正在使用的构造函数仅适用于将邮件发送给一位收件人,如您所述。您必须使用无参数构造函数。

var mail = new Mail();
mail.Subject = "subject";
mail.From = new Email("from@example.com", "fromName");
mail.AddContent(new Content("text/html", "<p>this is a mail<p>"));
mail.AddPersonalization(personalization);

通过Personalization对象添加实际收件人:

var personalization = new Personalization();
foreach (Email email in emailList)
{
    personalization.AddTo(email);
}

此个性化对象还允许进行更多自定义,例如将收件人添加为cc或bcc。

答案 1 :(得分:1)

您需要为此添加个性化列表。以下代码对我有用。

var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
    From = new EmailAddress("sender@email.com", "Sender Name"),
    Subject = "Subject",
    PlainTextContent = "Text for body",
    HtmlContent = "<strong>Hello World!",
    Personalizations = new List<Personalization>
    {
         new Personalization
         {
              Tos = new List<EmailAddress> 
              {
                   new EmailAddress("abc@email.com", "abc"),
                   new EmailAddress("efg@email.com", "efg")
              }
         }
     }
};

var response = await client.SendEmailAsync(msg);

有关更多详细信息,请查看Mail Send

答案 2 :(得分:0)

公共静态SendGridMessage CreateSingleEmailToMultipleRecipients(电子邮件地址来自,列表项,字符串主题,字符串plainTextContent,字符串htmlContent,布尔showAllRecipients = false);

答案 3 :(得分:0)

为多个收件人发送邮件语法:

命名空间: 使用 SendGrid; 使用 SendGrid.Helpers.Mail;

        syntax:
        
        var client = new SendGridClient("XXXXXXX");
        var msg = new SendGridMessage()
        {
            From = new EmailAddress("Yourmail@address", " your Address name"),
            Subject = subject,
            PlainTextContent = message,
            HtmlContent = message
        };
        
        var timeToSend=DateTime.Now 

// 将时间添加到日期时间参考 https://codesandbox.io/s/dynamic-form-item-antd4169-forked-dl8od

        if (timeToSend != null && timeToSend.Value.Date >= DateTime.Now.Date)
        {
            var offset = new DateTimeOffset(timeToSend.Value);
            long sendAtUnixTime = offset.ToUnixTimeSeconds();
            msg.SendAt = sendAtUnixTime;
        }
        var emails = to.Split(';');
        foreach (var email in emails)
        {
            msg.AddTo(new EmailAddress(email));
        }
        if (!string.IsNullOrEmpty(bcc))
        {
            msg.AddBcc(new EmailAddress(bcc));
        }
        var response = await client.SendEmailAsync(msg);