View source
<?php
namespace Drupal\swiftmailer\Plugin\Mail;
use Drupal\Component\Render\MarkupInterface;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Mail\MailFormatHelper;
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\key\KeyInterface;
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;
class SwiftMailer implements MailInterface, ContainerFactoryPluginInterface {
protected $config;
protected $logger;
protected $renderer;
protected $moduleHandler;
protected $transportFactory;
public function __construct(TransportFactoryInterface $transport_factory, ImmutableConfig $message, LoggerInterface $logger, RendererInterface $renderer, ModuleHandlerInterface $module_handler) {
$this->transportFactory = $transport_factory;
$this->config['message'] = $message
->get();
$this->logger = $logger;
$this->renderer = $renderer;
$this->moduleHandler = $module_handler;
}
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'));
}
public function format(array $message) {
$message = $this
->massageMessageBody($message);
$applicable_format = $this
->getApplicableFormat($message);
if ($applicable_format == SWIFTMAILER_FORMAT_HTML) {
$render = [
'#theme' => isset($message['params']['theme']) ? $message['params']['theme'] : 'swiftmailer',
'#message' => $message,
];
$message['body'] = $this->renderer
->renderPlain($render);
if (empty($message['plain']) && $this->config['message']['convert_mode'] || !empty($message['params']['convert'])) {
$converter = new Html2Text($message['body']);
$message['plain'] = $converter
->getText();
}
}
$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 = rand(0, 9999999999);
$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 = Swift_Message::newInstance($message['subject']);
$suppressable_headers = swiftmailer_get_supressable_headers();
$respect_format = $this->config['message']['respect_format'];
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' && (!$respect_format || 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']);
$applicable_format = $this
->getApplicableFormat($message);
$applicable_charset = $this
->getApplicableCharset($message);
$m
->setBody($message['body'], $applicable_format, $applicable_charset);
if ($applicable_format == 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 = Swift_Mailer::newInstance($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,
]);
\Drupal::messenger()
->addError(t('An attempt to send an e-mail message failed.'));
}
return FALSE;
}
private 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;
}
if (UrlHelper::isValid($file->uri, TRUE)) {
$content = file_get_contents($file->uri);
}
else {
$content = file_get_contents(\Drupal::service('file_system')
->realpath($file->uri));
}
$filename = $file->filename;
$filemime = $file->filemime;
$m
->attach(Swift_Attachment::newInstance($content, $filename, $filemime));
}
}
}
private 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(Swift_Attachment::newInstance($a['filecontent'], $a['filename'], $a['filemime']));
}
}
}
}
private 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(Swift_Image::newInstance($content, $filename, $filemime));
$body = $m
->getBody();
$body = preg_replace('/cid:' . $image->cid . '/', $cid, $body);
$m
->setBody($body);
}
}
}
private function getApplicableFormat($message) {
$default_format = $this->config['message']['format'];
$respect_format = $this->config['message']['respect_format'];
$applicable_format = !empty($message['params']['format']) ? $message['params']['format'] : $default_format;
if ($respect_format && !empty($message['headers']['Content-Type'])) {
$format = $message['headers']['Content-Type'];
if (preg_match('/.*\\;/U', $format, $matches)) {
$applicable_format = trim(substr($matches[0], 0, -1));
}
else {
$applicable_format = $message['headers']['Content-Type'];
}
}
return $applicable_format;
}
private function getApplicableCharset($message) {
$default_charset = $this->config['message']['character_set'];
$respect_charset = $this->config['message']['respect_format'];
$applicable_charset = !empty($message['params']['charset']) ? $message['params']['charset'] : $default_charset;
if ($respect_charset && !empty($message['headers']['Content-Type'])) {
$format = $message['headers']['Content-Type'];
$format = preg_match('/charset.*=.*\\;/U', $format, $matches);
if ($format > 0) {
$applicable_charset = trim(substr($matches[0], 0, -1));
$applicable_charset = preg_replace('/charset=/', '', $applicable_charset);
}
else {
$applicable_charset = $default_charset;
}
}
return $applicable_charset;
}
public function massageMessageBody(array $message) {
$line_endings = Settings::get('mail_line_endings', PHP_EOL);
$applicable_format = $this
->getApplicableFormat($message);
$filter_format = $this->config['message']['filter_format'];
$message['body'] = Markup::create(implode($line_endings, array_map(function ($body) use ($applicable_format, $filter_format) {
if ($applicable_format == SWIFTMAILER_FORMAT_HTML && mb_strlen(strip_tags($body)) === mb_strlen($body)) {
$build = [
'#type' => 'processed_text',
'#text' => $body,
'#format' => $filter_format,
];
$body = $this->renderer
->renderPlain($build);
}
return $body instanceof MarkupInterface ? $body : MailFormatHelper::htmlToText($body);
}, $message['body'])));
return $message;
}
}