我正在使用此代码从Web应用程序发送电子邮件。仅一个收件人就没问题。我已经研究过使用来自https://sendgrid.com/docs/Integrate/Code_Examples/v3_Mail/csharp.html的相同技术将电子邮件发送给多个收件人。我尝试用逗号分隔的字符串作为destinatario(请参见代码中的args),即you @ example.com,she @ example.com,he @ example.com,但SendGrid仅接受第一个收件人。我也尝试过使用数组,但结果是类似的,SG只接受最后一个收件人。传递收件人列表的正确方法是什么?
public class email
{
public void enviar(string destinatario, string asunto, string contenido)
{
Execute(destinatario, asunto, contenido).Wait();
}
static async Task Execute(string destinatario, string asunto, string contenido)
{
string apiKey = "SG...............";
dynamic sg = new SendGridAPIClient(apiKey);
Email from = new Email("someone@example.com");
string subject = asunto;
Email to = new Email(destinatario);
Content content = new Content("text/plain", contenido);
Mail mail = new Mail(from, subject, to, content);
dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
}
}
Run Code Online (Sandbox Code Playgroud)
rez*_*e08 12
您需要为此添加个性化列表。以下代码对我有用。
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);
Run Code Online (Sandbox Code Playgroud)
欲了解更多详情,请查看以下邮件发送
小智 1
您的问题的答案可以在库的源代码中找到,有两个构造函数来创建 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);
Run Code Online (Sandbox Code Playgroud)
实际的收件人是通过Personalization对象添加的:
var personalization = new Personalization();
foreach (Email email in emailList)
{
personalization.AddTo(email);
}
Run Code Online (Sandbox Code Playgroud)
此个性化对象还允许更多自定义,例如将收件人添加为抄送或密件抄送。