Skip to content

Instantly share code, notes, and snippets.

@agarwa13
Last active November 5, 2015 02:23
Show Gist options
  • Save agarwa13/3bad73e00bf6e18108e8 to your computer and use it in GitHub Desktop.
Save agarwa13/3bad73e00bf6e18108e8 to your computer and use it in GitHub Desktop.
Laravel 5.1 Event Listener that prevents emails from being sent to email addresses that have bounced previously.
<?php
// Filter Emails in the Bounce List
Event::listen('mailer.sending',function(\Swift_Message $swiftype_message){
// Get the Original Recipients of the Mail
$recipients = $swiftype_message->getTo();
// Log::info('Original Recepients: '.json_encode($recipients));
// Check if Any of the Email Addresses are in the Problem Emails Database
$email_addresses = array_keys($recipients);
$problem_emails = ProblemEmail::whereIn('email_address',$email_addresses)->get();
// Log::info('Problem Emails: '.json_encode($problem_emails));
// Remove all the Problem Emails from the Recipients List
foreach($problem_emails as $problem_email){
unset($recipients[$problem_email->email_address]);
}
// Log::info('Final Emails: '.json_encode($recipients));
// Set the Recipients List Once Again
// If the Number of recipients is less than 1, send a pretend mail
// We do this, because sending a mail to 0 recipients throws an error
if(count($recipients) > 0){
$swiftype_message->setTo($recipients);
}else{
Mail::pretend();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment