You cannot pass strings like "User <user@example.com>" to send emails, I know.
My only question is whether Swiftmailer somewhere provides any functionality to extract name and email from such RFC 2822 strings? I guess not, but just want to double check. Thanks.
Parsing strings like "User <user@example.com>&quo
Moderators: Chris Corbyn, General Moderators
- Kieran Huggins
- DevNet Master
- Posts: 3635
- Joined: Wed Dec 06, 2006 4:14 pm
- Location: Toronto, Canada
- Contact:
That's exactly why I needed those RFC 2822 strings, to create a drop-in replacement for PHP's native mail function (view Kohana's mail helper).
Why not support that format? I would say that it is cleaner to keep email addresses and names separated while coding.
Why not support that format? I would say that it is cleaner to keep email addresses and names separated while coding.
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
It used to. I dropped allowing that syntax and simply rendering it myself from a name <-> email pair because it was just causing too much confusion with users on how to structure such a string and was resulting in too many support queries. There were a few things changed partly to reduce the number of support queries I was getting. Another was the use of exceptions with descriptive errors instead of silently failing and requiring a getErrors() method be used.Kieran Huggins wrote:Sounds like a job for regex to me!
Incidentally, the mail() function supports that syntax, why does swift not? Maybe Chris can shed some light?
It's pretty easy to parse that string out though. There's a method in the EasySwift class to do it. You'll have to tweak it to return an array instead of a Swift Address object though. I'm at work right now so don't have much time to play I'm afraid
Here's the CHEAP_ADDRESS_RE it uses:
Code: Select all
/**
* A regular expression which matches valid e-mail addresses (including some unlikely ones)
*/
const CHEAP_ADDRESS_RE = '(?#Start of dot-atom
)[-!#\$%&\'\*\+\/=\?\^_`{}\|~0-9A-Za-z]+(?:\.[-!#\$%&\'\*\+\/=\?\^_`{}\|~0-9A-Za-z]+)*(?#
End of dot-atom)(?:@(?#Start of domain)[-0-9A-Za-z]+(?:\.[-0-9A-Za-z]+)*(?#End of domain))?';Code: Select all
/**
* Turn a string representation of an email address into a Swift_Address object
* @paramm string The email address
* @return Swift_Address
*/
public function stringToAddress($string)
{
$name = null;
$address = null;
// Foo Bar <foo@bar>
// or: "Foo Bar" <foo@bar>
// or: <foo@bar>
Swift_ClassLoader::load("Swift_Message_Encoder");
if (preg_match("/^\\s*("?)(.*?)\\1 *<(" . Swift_Message_Encoder::CHEAP_ADDRESS_RE . ")>\\s*\$/", $string, $matches))
{
if (!empty($matches[2])) $name = $matches[2];
$address = $matches[3];
}
elseif (preg_match("/^\\s*" . Swift_Message_Encoder::CHEAP_ADDRESS_RE . "\\s*\$/", $string))
{
$address = trim($string);
}
else return false;
$swift_address = new Swift_Address($address, $name);
return $swift_address;
}