Inline CSS in the HTML output of SwiftMailer using Emogrifier.
Install via composer, using:
composer require bummzack/swiftmailer-emogrifyplugin
Requirements:
- PHP 5.6+
- SwiftMailer 5.x
- Emogrifier 2.x
By default, the plugin will inline CSS that is part of the HTML, eg. styles defined in <style>
tags.
You can instantiate the plugin with your own Emogrifier
instance or change properties of the emogrifier instance.
For a list of options, please head over to the Emogrifier documentation.
Please note, that the plugin is using one instance of Emogrifier
to convert all message-parts,
so the settings you make apply to all converted html parts.
$plugin = new EmogrifierPlugin();
$plugin->getEmogrifier()->setCss('.customStyle: { color: red; };');
Please note: Calling setHtml
on the Emogrifier instance doesn't have an effect, since it will be replaced with
the message body!
Here's how you could use the plugin to send emails with custom styles loaded from a file:
$emogrifier = new Pelago\Emogrifier();
$emogrifier->setCss(file_get_contents( /* path to your CSS file */ ));
// Create the Mailer using any Transport
$mailer = new Swift_Mailer(
new Swift_SmtpTransport('smtp.example.org', 25)
);
// Use Emogrifier plugin to inline styles. You can pass the emogrifier instance as a parameter
$mailer->registerPlugin(new Bummzack\SwiftMailer\EmogrifyPlugin\EmogrifierPlugin($emogrifier));
$message = new Swift_Message();
$message
->setSubject('Your subject')
->setFrom(['[email protected]' => 'Test'])
->setTo(['[email protected]'])
->setBody('<p>My custom HTML</p>', 'text/html');
// Send your email
$mailer->send($message);