SendGrid:向“多个收件人”发送电子邮件,而“收件人”字段中不显示其他电子邮件

时间:2017-05-09 13:55:08

标签: php sendgrid sendgrid-api-v3

我想向多个收件人发送电子邮件。

我使用了personalizations,但每个人的电子邮件都出现在“收件人”字段中,这违反了他们的隐私权。

我不想使用BCC,因为这通常直接导致垃圾(例如http://www.standss.com/blog/index.php/why-you-should-avoid-using-bcc-for-emails/)。

因此,我的问题是,如何在没有每个人电子邮件出现在“收件人”字段中的情况下向多个收件人发送电子邮件。

我能看到的唯一选择是使用循环向每个电子邮件发送一个单独的请求,当我发送大量电子邮件时,这是非常耗费资源和耗时的!

3 个答案:

答案 0 :(得分:5)

将SendGrid的个性化设置与多个收件人组一起使用时,您需要定义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调用中,然后发送。

答案 1 :(得分:0)

要构建@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())

答案 2 :(得分:0)

这是一个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;
    }