View source
<?php
namespace Drupal\swiftmailer\Plugin\Mail;
use Drupal\Component\Render\MarkupInterface;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Random;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Asset\AssetResolverInterface;
use Drupal\Core\Asset\AttachedAssets;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Mail\MailInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\Markup;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Site\Settings;
use Drupal\swiftmailer\TransportFactoryInterface;
use Drupal\swiftmailer\Utility\Conversion;
use Exception;
use Html2Text\Html2Text;
use Psr\Log\LoggerInterface;
use stdClass;
use Swift_Attachment;
use Swift_Image;
use Swift_Mailer;
use Swift_Message;
use Symfony\Component\DependencyInjection\ContainerInterface;
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;
use Drupal\Core\Theme\ThemeManagerInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\mailsystem\MailsystemManager;
class SwiftMailer implements MailInterface, ContainerFactoryPluginInterface {
protected $config;
protected $logger;
protected $renderer;
protected $moduleHandler;
protected $transportFactory;
protected $mailManager;
protected $themeManager;
protected $assetResolver;
public function __construct(TransportFactoryInterface $transport_factory, ImmutableConfig $message, LoggerInterface $logger, RendererInterface $renderer, ModuleHandlerInterface $module_handler, MailManagerInterface $mail_manager, ThemeManagerInterface $theme_manager, AssetResolverInterface $asset_resolver) {
$this->transportFactory = $transport_factory;
$this->config['message'] = $message
->get();
$this->logger = $logger;
$this->renderer = $renderer;
$this->moduleHandler = $module_handler;
$this->mailManager = $mail_manager;
$this->themeManager = $theme_manager;
$this->assetResolver = $asset_resolver;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($container
->get('swiftmailer.transport'), $container
->get('config.factory')
->get('swiftmailer.message'), $container
->get('logger.factory')
->get('swiftmailer'), $container
->get('renderer'), $container
->get('module_handler'), $container
->get('plugin.manager.mail'), $container
->get('theme.manager'), $container
->get('asset.resolver'));
}
public function format(array $message) {
$is_html = $this
->getContentType($message) == SWIFTMAILER_FORMAT_HTML;
$generate_plain = $message['params']['generate_plain'] ?? $message['params']['convert'] ?? $this->config['message']['generate_plain'];
if ($generate_plain && empty($message['plain']) && $is_html) {
$saved_body = $message['body'];
$this
->massageMessageBody($message, FALSE);
$message['plain'] = $message['body'];
$message['body'] = $saved_body;
}
$this
->massageMessageBody($message, $is_html);
$random = new Random();
$embeddable_images = [];
$processed_images = [];
preg_match_all('/"image:([^"]+)"/', $message['body'], $embeddable_images);
for ($i = 0; $i < count($embeddable_images[0]); $i++) {
$image_id = $embeddable_images[0][$i];
if (isset($processed_images[$image_id])) {
continue;
}
$image_path = trim($embeddable_images[1][$i]);
$image_name = basename($image_path);
if (mb_substr($image_path, 0, 1) == '/') {
$image_path = mb_substr($image_path, 1);
}
$image = new \stdClass();
$image->uri = $image_path;
$image->filename = $image_name;
$image->filemime = \Drupal::service('file.mime_type.guesser')
->guess($image_path);
$image->cid = $random
->name(8, TRUE);
$message['params']['images'][] = $image;
$message['body'] = preg_replace($image_id, 'cid:' . $image->cid, $message['body']);
$processed_images[$image_id] = 1;
}
return $message;
}
public function mail(array $message) {
try {
$m = new Swift_Message($message['subject']);
$suppressable_headers = swiftmailer_get_supressable_headers();
if (!empty($message['headers']) && is_array($message['headers'])) {
foreach ($message['headers'] as $header_key => $header_value) {
if (empty($header_key) || in_array($header_key, $suppressable_headers)) {
continue;
}
if ($header_key == 'Content-Type' && swiftmailer_is_multipart($message)) {
continue;
}
$header_type = Conversion::swiftmailer_get_headertype($header_key, $header_value);
switch ($header_type) {
case SWIFTMAILER_HEADER_ID:
Conversion::swiftmailer_add_id_header($m, $header_key, $header_value);
break;
case SWIFTMAILER_HEADER_PATH:
Conversion::swiftmailer_add_path_header($m, $header_key, $header_value);
break;
case SWIFTMAILER_HEADER_MAILBOX:
Conversion::swiftmailer_add_mailbox_header($m, $header_key, $header_value);
break;
case SWIFTMAILER_HEADER_DATE:
Conversion::swiftmailer_add_date_header($m, $header_key, $header_value);
break;
case SWIFTMAILER_HEADER_PARAMETERIZED:
Conversion::swiftmailer_add_parameterized_header($m, $header_key, $header_value);
break;
default:
Conversion::swiftmailer_add_text_header($m, $header_key, $header_value);
break;
}
}
}
Conversion::swiftmailer_add_mailbox_header($m, 'To', $message['to']);
$content_type = $this
->getContentType($message);
$applicable_charset = $this
->getApplicableCharset($message);
$m
->setBody($message['body'], $content_type, $applicable_charset);
if ($content_type == SWIFTMAILER_FORMAT_HTML && !empty($message['plain'])) {
$m
->addPart($message['plain'], SWIFTMAILER_FORMAT_PLAIN, $applicable_charset);
}
if (empty($message['params']['files']) || !is_array($message['params']['files'])) {
$message['params']['files'] = [];
}
$files = $this->moduleHandler
->invokeAll('swiftmailer_attach', [
'key' => $message['key'],
'message' => $message,
]);
if (!empty($files) && is_array($files)) {
$message['params']['files'] = array_merge(array_values($message['params']['files']), array_values($files));
}
if (!empty($message['params']['files']) && is_array($message['params']['files'])) {
$this
->attach($m, $message['params']['files']);
}
if (!empty($message['params']['attachments']) && is_array($message['params']['attachments'])) {
$this
->attachAsMimeMail($m, $message['params']['attachments']);
}
if (!empty($message['params']['images']) && is_array($message['params']['images'])) {
$this
->embed($m, $message['params']['images']);
}
$transport_type = $this->transportFactory
->getDefaultTransportMethod();
$transport = $this->transportFactory
->getTransport($transport_type);
$mailer = new Swift_Mailer($transport);
$this->moduleHandler
->alter('swiftmailer', $mailer, $m, $message);
Conversion::swiftmailer_filter_message($m);
return (bool) $mailer
->send($m);
} catch (Exception $e) {
$headers = !empty($m) ? $m
->getHeaders() : '';
$headers = !empty($headers) ? nl2br($headers
->toString()) : 'No headers were found.';
$this->logger
->error('An attempt to send an e-mail message failed, and the following error
message was returned : @exception_message<br /><br />The e-mail carried
the following headers:<br /><br />@headers', [
'@exception_message' => $e
->getMessage(),
'@headers' => $headers,
]);
}
return FALSE;
}
protected function attach(Swift_Message $m, array $files) {
foreach ($files as $file) {
if ($file instanceof stdClass) {
if (empty($file->uri) || empty($file->filename) || empty($file->filemime)) {
continue;
}
$content = file_get_contents($file->uri);
$filename = $file->filename;
$filemime = $file->filemime;
$m
->attach(new Swift_Attachment($content, $filename, $filemime));
}
}
}
protected function attachAsMimeMail(Swift_Message $m, array $attachments) {
foreach ($attachments as $a) {
if (is_array($a)) {
if (empty($a['filepath']) && empty($a['filecontent'])) {
continue;
}
if (empty($a['filename']) || empty($a['filemime'])) {
continue;
}
if (!empty($a['filepath'])) {
$file = new stdClass();
$file->uri = $a['filepath'];
$file->filename = $a['filename'];
$file->filemime = $a['filemime'];
$this
->attach($m, [
$file,
]);
}
else {
$m
->attach(new Swift_Attachment($a['filecontent'], $a['filename'], $a['filemime']));
}
}
}
}
protected function embed(Swift_Message $m, array $images) {
foreach ($images as $image) {
if ($image instanceof stdClass) {
if (empty($image->uri) || empty($image->filename) || empty($image->filemime) || empty($image->cid)) {
continue;
}
$cid = NULL;
if (UrlHelper::isValid($image->uri, TRUE)) {
$content = file_get_contents($image->uri);
}
else {
$content = file_get_contents(\Drupal::service('file_system')
->realpath($image->uri));
}
$filename = $image->filename;
$filemime = $image->filemime;
$cid = $m
->embed(new Swift_Image($content, $filename, $filemime));
$body = $m
->getBody();
$body = preg_replace('/cid:' . $image->cid . '/', $cid, $body);
$m
->setBody($body);
}
}
}
protected function getContentType(array $message) {
$content_type = $message['params']['content_type'] ?? $message['params']['format'] ?? $this->config['message']['content_type'];
if ($content_type) {
return $content_type;
}
if (isset($message['headers']['Content-Type'])) {
return explode(';', $message['headers']['Content-Type'])[0];
}
return 'text/plain';
}
protected function getApplicableCharset(array $message) {
return $message['params']['charset'] ?? $this->config['message']['character_set'];
}
protected function massageMessageBody(array &$message, $is_html) {
$text_format = $message['params']['text_format'] ?? $this->config['message']['text_format'] ?: NULL;
$line_endings = Settings::get('mail_line_endings', PHP_EOL);
$body = [];
foreach ($message['body'] as $part) {
if (!$part instanceof MarkupInterface) {
if ($is_html) {
$body[] = check_markup($part, $text_format);
}
else {
$body[] = preg_replace("|\n|", "<br />\n", HTML::escape($part)) . "<br />\n";
}
}
else {
$body[] = $part . $line_endings;
}
}
$message['body'] = Markup::create(implode('', $body));
if ($this->mailManager instanceof MailsystemManager) {
$mail_theme = $this->mailManager
->getMailTheme();
}
else {
$mail_theme = $this->themeManager
->getActiveTheme()
->getName();
}
$render = [
'#theme' => $message['params']['theme'] ?? 'swiftmailer',
'#message' => $message,
'#is_html' => $is_html,
];
if ($is_html) {
$render['#attached']['library'] = [
"{$mail_theme}/swiftmailer",
];
}
$message['body'] = $this->renderer
->renderPlain($render);
if ($is_html) {
$assets = AttachedAssets::createFromRenderArray($render);
$css = '';
foreach ($this->assetResolver
->getCssAssets($assets, TRUE) as $css_asset) {
$css .= file_get_contents($css_asset['data']);
}
if ($css) {
$message['body'] = (new CssToInlineStyles())
->convert($message['body'], $css);
}
}
else {
$message['body'] = (new Html2Text($message['body']))
->getText();
}
}
}