Question

I am using the Swiftmailer in my Symfony2 webapp.

// Subject and body dynamically come from database
$subject  = "This is my subject with an apostroph ' in it.";
$bodytext = "Test text, also with an ' apostrophe in it.";

$message = \Swift_Message::newInstance()
             ->setSubject($subject)
             ->setFrom('me@mail.com')
             ->setTo('you@mail.com');

$message->setBody($bodytext);

$this->get('mailer')->send($message);

Now when there is a special char, e.g. the apostrophe (') in my subject, the email has a strange subject line in my email client:

This is my subject with an apostroph ' in it

Funny thing: The body text is displayed correctly, it's only the subject that's wrongly formatted.

Now how can I handle special chars like this - and even better, is there a function I can call before passing the subject that handles special chars in general?

Was it helpful?

Solution

Try to escape the subject with the htmlentities PHP function:

$subject  = htmlentities("This is my subject with an apostroph ' in it.");

OTHER TIPS

Sorry, I know this is late but it might help anyone still having these similar issues. I was having issues with apostrophe ' and ampersand & on SwiftMailer 6.2 so combining both htmlspecialchars_decode and html_entity_decode to convert the subject resolved it for me:

->setSubject(htmlspecialchars_decode(html_entity_decode($subject), ENT_QUOTES))

See https://www.php.net/manual/en/function.html-entity-decode.php and https://www.php.net/manual/en/function.htmlspecialchars-decode.php for further explanations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top