Sendgrid批量发送电子邮件php

时间:2016-02-28 15:46:24

标签: php swiftmailer sendgrid

我尝试使用带有Swiftmailer(5.4)的Sendgrid SMTP API(4.0)向已导入新网站的用户发送大量密码重置链接。

以下代码有效,但每个收件人都可以看到完整列表电子邮件,因为它们都在“收件人:”字段中。 如何使用模板和替换一次发送多封电子邮件,而不是每个收件人都可以看到所有电子邮件地址。 BCC过滤器似乎只收到一封电子邮件。

<?php

$links = array('reset link 1', 'reset link 2');
$emails = array( 'example1@gmail.com', 'example2@gmail.com' );

$transport = \Swift_SmtpTransport::newInstance( 'smtp.sendgrid.net', 587 );
$transport->setUsername( 'username' );
$transport->setPassword( 'password' );

$mailer = \Swift_Mailer::newInstance( $transport );

$message = new \Swift_Message();
$response = $mailer->send( $message );
$message->setTo( $emails );
$message->setFrom( 'info@newwebsite.ie' );
$message->setBody( 'body content' );

$header = new Smtpapi\Header();
$header->addSubstitution( '%name%', $names );
$header->addSubstitution( '%source%', $sources );
$header->addSubstitution( '%link%', $links );

$filter = array(
  'templates' => array(
    'settings'  => array(
      'enable'          => 1,
      'template_id' => 'cc813g53-template-id'
    )
  )
);
$header->setFilters( $filter );
$message_headers = $message->getHeaders();
$message_headers->addTextHeader( HEADER::NAME,   $header->jsonString(JSON_UNESCAPED_UNICODE) );

try {
    $response = $mailer->send( $message );
    print_r( $response ); //2 emails sent
} catch(\Swift_TransportException $e) {
    print_r('Bad username / password');
}

?>

1 个答案:

答案 0 :(得分:0)

为防止收件人看到完整的电子邮件列表,您可以像这样循环每封邮件(未经测试的代码):

<?php
$emails = array( 'example1@gmail.com', 'example2@gmail.com' );

$transport = \Swift_SmtpTransport::newInstance( 'smtp.sendgrid.net', 587 );
$transport->setUsername( 'username' );
$transport->setPassword( 'password' );
// You may need to move the mailer inside the foreach loop (untested).
$mailer = \Swift_Mailer::newInstance( $transport );

foreach ($emails as $email) {
    $links = array('reset link 1', 'reset link 2');

    $message = new \Swift_Message();
    $response = $mailer->send( $message );
    $message->setTo( $email );
    $message->setFrom( 'info@newwebsite.ie' );
    $message->setBody( 'body content' );

    $header = new Smtpapi\Header();
    $header->addSubstitution( '%name%', $names );
    $header->addSubstitution( '%source%', $sources );
    $header->addSubstitution( '%link%', $links );

    $filter = array(
      'templates' => array(
        'settings'  => array(
          'enable'          => 1,
          'template_id' => 'cc813g53-template-id'
        )
      )
    );
    $header->setFilters( $filter );
    $message_headers = $message->getHeaders();
    $message_headers->addTextHeader( HEADER::NAME,   $header->jsonString(JSON_UNESCAPED_UNICODE) );

    try {
        $response = $mailer->send( $message );
        print_r( $response ); //2 emails sent
    } catch(\Swift_TransportException $e) {
        print_r('Bad username / password');
    }
}
?>