Reputation: 60
I'm attempting to use the Sendgrid SMTP API (4.0) with Swiftmailer (5.4) to send mass password reset links to users that have been imported into a new site .
The code below works, but every recipient can see the full list emails as they are all in the To: field. How can I send multiple emails at once using templates and substitutions without all email addresses being visible to each recipient. The BCC filter appears to take only one email.
<?php
$links = array('reset link 1', 'reset link 2');
$emails = array( '[email protected]', '[email protected]' );
$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( '[email protected]' );
$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');
}
?>
Upvotes: 1
Views: 761
Reputation: 4104
To prevent recipients from seeing the full list of e-mails, you can loop each mail like this (untested code):
<?php
$emails = array( '[email protected]', '[email protected]' );
$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( '[email protected]' );
$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');
}
}
?>
Upvotes: 1