Carey Estes Carey Estes - 5 months ago 6x
PHP Question

How to extend MailboxHeader.php in Swift Mailer or validate emails

I am working with SYmfony 1.4 and swift mailer to send a bulk array of emails through Sendgrid.

I am getting an RFC compliance error on some of the email addresses.

One solution would be to remove the condition to throw the error, and it does work, but it involves changing the core. How would you extend MailboxHeader.php in the site files and not the symfony core. Something like this, but not this because it doesn't work:

class overrideRFCError extends Swift_Mime_Headers_AbstractHeader
private function _assertValidAddress($address)
if (!preg_match('/^' . $this->getGrammar('addr-spec') . '$/D',
// throw new Swift_RfcComplianceException(
// 'Address in mailbox given [' . $address .
// '] does not comply with RFC 2822, 3.6.2.'
// );

This also seems a little heavy handed. Is there a way to validate the email for RFC compliance. If so, I could then just unset it from the array.

UPDATE 07/17/13

I was able to put a thorough cleaning on each address to make it RFC compliant, which solves the problem. However, I would like to know if a function exists in the SwiftMailer that does this check, rather then writing a custom function.

UPDATE 07/18/13

Here is what I got to work. I tried to sanitize the entries as much as possible.

Load an array of addresses in a variable called

in actions:

$cleanList = sendGridEmailer::validateEmails($emailList);

in sendGridEmailer class:

// loop and validate each email address
public static function validateEmails($emailList) {
foreach($emailList as $address => $name) {
try {
$v = new sfValidatorEmail();
$email = $v->clean($address);

} catch (sfValidatorError $e) {
foreach($emailList as $address => $name) {
$rfcTesting = validateEmailForRFC::is_email($address);
if(!$rfcTesting) {
if (!preg_match('/^[a-zA-Z0-9_.-@]/', $address)) {
// List should be clean
return $emailList;

So this first uses the sfValidator to kick out the initial bad addresses. Next, I got a RFC compliance script here and execute that in the validateEmailForRFC class which should make them RFC Compliant.

Last, I do a final pregmatch for any stragglers with weird chars that the previous checks did not catch.

This allowed me to keep the Symfony core untouched and prepped the addresses for Swift with no Compliance errors.

1ed 1ed

You can use symfony's sfValidatorEmail or the filter-var function. They work good enough with SwiftMailer, but neither of them are RFC compliant IIRC. For validating against RFCs you can use or