我想向多个收件人发送一封电子邮件。
我用的是personalizations,但每个人的电子邮件都会出现在“收件人”栏上,这侵犯了他们的隐私。
我不想使用密件抄送,因为这通常会直接变成垃圾(例如http://www.standss.com/blog/index.php/why-you-should-avoid-using-bcc-for-emails/)。
因此,我的问题是,我如何向多个收件人发送电子邮件,而每个人的电子邮件都显示在“收件人”字段中。
我能看到的唯一的选择是使用循环为每一封电子邮件发送一个单独的请求到API,当我有很多电子邮件要发送时,这是非常耗费资源和时间的!
发布于 2017-05-10 03:09:59
当对多个收件人组使用SendGrid的Personalization时,您需要定义multiple 1st-level objects within the Personalization array。
因此,不是:
{"personalizations": [
{"to": [
{"email": "recipient1@example.com"},
{"email": "recipient2@example.com"}
]}]}
它们都将是可彼此看见的公共To:
阵列,
您需要:
{"personalizations": [
{"to": [{"email": "recipient1@example.com"}]},
{"to": [{"email": "recipient2@example.com"}]}
]}
在每个个性化级别中,您可以自定义内容、主题、替换标记,几乎所有内容。
因此,您可以构建完整的个性化,并遍历这些1000次。一旦你有了1000个收件人,将他们捆绑到一个API调用中,然后发送它。
发布于 2018-06-09 02:52:26
这是一个C#版本,它克隆了每个收件人的个性化信息,但仍然只有一个SendGrid API调用:
public static void SendEachReceipient(SendGridMessage msg, IEnumerable<string> recipients)
{
if (msg == null || recipients == null || !recipients.Any())
return;
if (msg.Personalizations == null) //can easily be null if no substitutions have not been added
msg.Personalizations = new List<Personalization>();
var substitutionsCopy = msg.Personalizations.FirstOrDefault()?.Substitutions; //all substitutions (if any) are always all contained in the first personalization
msg.Personalizations.Clear(); //we will start fresh - one personalization per each receipient to keep emails private from each other
foreach (var email in recipients.Where(x => !string.IsNullOrEmpty(x)).Distinct())
{
var personalization = new Personalization();
personalization.Substitutions = substitutionsCopy;
personalization.Tos = new List<EmailAddress>() { new EmailAddress(email) };
msg.Personalizations.Add(personalization);
}
var result = new SendGridClient("api-key").SendEmailAsync(msg).Result;
}
发布于 2018-06-02 21:10:28
为了构建@jacobmovingfwd,这里有一个Python示例,它使用个性化的" To“字段将相同的电子邮件发送给多个收件人。我已经测试了代码,它对我来说是有效的。
# Given a list of email addresses that are strings
sublist = [...]
mail = Mail()
for to_email in sublist:
# Create new instance for each email
personalization = Personalization()
# Add email addresses to personalization instance
personalization.add_to(Email(to_email))
# Add personalization instance to Mail object
mail.add_personalization(personalization)
# Add data that is common to all personalizations
mail.from_email = Email(from_email)
mail.subject = subject
mail.add_content(Content('text/plain', message_txt))
mail.add_content(Content('text/html', message_html))
# Send
sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
response = sg.client.mail.send.post(request_body=mail.get())
https://stackoverflow.com/questions/43871807
复制相似问题