Search code examples
phptinymceswiftmaileremail-client

Text formatting doesn't appear in emails that have been formatted using TinyMCE and sent using SwiftMailer


I use SwiftMailer in my PHP scripts to send emails and I use TinyMCE as a text editor to write and format the message body. The problem is that when I send the message it appears without any formatting in all email clients (gmail, yahoo and hotmail), and even links doesn't appear as links, they appear as normal text but in blue. so what is the problem?

Here is the code I use to send emails:

<?php

require_once 'path/to/SwiftMailer/lib/swift_required.php';

$transport = Swift_MailTransport::newInstance();
# Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
# Create the message
$msg = Swift_Message::newInstance();
# Give the message a subject
$msg->setSubject($_POST['subject']);
# Set the From address with an associative array
$msg->setFrom(array($_POST['sender_email'] => $_POST['sender_name']));
# Give it a body
$msg->setBody($_POST['message'], 'text/html');

$failedRecipients = array();
$numSent = 0;
$to = array(
    '[email protected]',
    '[email protected]' => 'Recipient 2',
    '[email protected]',
    '[email protected]' => 'Recipient 4',
    '[email protected]'
);

foreach ($to as $address => $name) {
    if (is_int($address)) {
        $msg->setTo($name);
    } else {
        $msg->setTo(array($address => $name));
    }

    $numSent += $mailer->send($msg, $failedRecipients);
}

echo $numSent > 0 ? 'SUCCESS' : 'FAILURE';

?>

note that $_POST['message'] holds body of the message that I have written and formatted using TinyMCE.


Solution

  • I have tried many things till I figure it out, the problem was that special characters in the formatted message body was being escaped (a back slash was being added in the front of each special character) I don't know why, and I don't know which of them (TinyMCE or SwiftMailer) that did this. So all I needed to do is to strip slashes out of the message body before sending the message throught SwiftMailer. I have just needed to change this line:

    $msg->setBody($_POST['message'], 'text/html');
    

    to be:

    $msg->setBody(stripslashes($_POST['message']), 'text/html');