0

I'm trying to send mail using SwiftMailer. My problem is the format in which I'm getting the from and to address is like this:

$from = '"first last" <email@domain.com>';

But when I use this

$message = Swift_Message::newInstance()->setFrom($from);

I get the following error:

Address in mailbox given ["first last" <email@domain.com>] does not comply with RFC 2822, 3.6.2

I think it is because Swift mailer excepts the format to be

 $message = Swift_Message::newInstance()->setFrom(['email@domain.com' => 'First Last']);

So my question is how do I convert

    "first last" <email@domain.com> => ['email@domain.com' => 'First Last']

I can use regex but there can be many cases like if quotes are not present, if email is with and without angular brackets, etc?

What is the best most foolproof way to do this?

Edit: Adding some more info for clarification

The from and to email are what the users are saving in the database, they are coming in many formats like "name" <email>, name <email>, <email>, or sometimes just email. I want to normalize all these string inputs to something that I can pass to Swift_Message::newInstance()->setFrom function

supersan
  • 5,671
  • 3
  • 45
  • 64
  • `$from = "first last" ;` is a syntax error. What's your *actual* code? – ceejayoz Oct 11 '16 at 22:33
  • From where does this string come? There is no way to check if everything is present before sending it? – LoïcR Oct 11 '16 at 22:35
  • actually `$from` comes from database but the format is like this only.. I've corrected the syntax. The actual code is pretty much this `$message = Swift_Message::newInstance()->setFrom('"first last" ');` – supersan Oct 11 '16 at 22:36
  • @Sakuto: the `from` and `to` email are what the users are saving in the database, they are coming in many formats like `"name" `, `name `, ``, or sometimes just `email`. I want to normalize all these inputs to something that I can pass to `Swift_Message::newInstance()->setFrom` function – supersan Oct 11 '16 at 22:38

0 Answers0