Используйте вложение для текста / HTML и текста / обычного с SwiftMailer
Я использую swiftmailer для отправки электронных писем, и я хотел бы иметь такое же вложение для:
* HTML-версии (text/html
) как встроенное изображение (cid)
* Текстовая версия (text/plain
) как приложение
Я тестирую электронную почту с помощью Mozilla Thunderbird 45.3.0 в Ubuntu.
Я играл с ->setBody
, ->addPart
, ->embed
а также ->attach
методы, но я всегда ломал одну из версий (т.е. получаю электронное письмо в виде обычного текста, или я рассматриваю сообщение как HTML или текстовое).
Мой тестовый код выглядит следующим образом (с допустимым SMTP-адресом и путем к файлу, конечно):
function swiftMail() {
require_once './vendor/swiftmailer/swiftmailer/lib/swift_required.php';
//Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.mail.com', 25);
//Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create the message
$message = Swift_Message::newInstance()
// Give the message a subject
->setSubject('SwiftMailer test // ' . uniqid('', true))
// Set the From address with an associative array
->setFrom(array('first.name@mail.com' => 'Me'))
// Set the To addresses with an associative array
->setTo(array('first.name@mail.com' => 'Me'));
// attach the image as attachment
$message->attach(Swift_Attachment::fromPath('./path/to/file.png')->setFilename('cool_image.png'));
// set the email's body as plain text
$message->setBody('My amazing body in plain text', 'text/plain');
// add the email's HTML part to the message
$message->addPart(
'<!doctype html>' .
'<html>' .
' <head><meta charset="UTF-8"></head>' .
' <body>' .
' Here is an image <br />'.
' <img src="' . $message->embed(Swift_Image::fromPath('./path/to/file.png')->setFilename('inline_cool_image.png')) . '" alt="Inline Image" /><br />' .
' Rest of message' .
' </body>' .
'</html>',
'text/html' // Mark the content-type as HTML
);
// send the message
if (!$mailer->send($message, $failures))
{
echo "Failures:";
print_r($failures);
}
}
Следующий код приводит к двум вложениям (что может быть хорошо) и только доступной текстовой версии (что не хорошо).
Есть ли способ использовать вложения в качестве встроенного источника изображений HTML и в качестве стандартного вложения в текстовом электронном письме?
2 ответа
Я столкнулся с точно такой же проблемой и смог ее исправить, добавив часть открытого текста с addPart()
вместо setBody()
,
$message->addPart('My amazing body in plain text', 'text/plain');
Исходя из вашего примера, это будет:
function swiftMail() {
require_once './vendor/swiftmailer/swiftmailer/lib/swift_required.php';
//Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.mail.com', 25);
//Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create the message
$message = Swift_Message::newInstance()
// Give the message a subject
->setSubject('SwiftMailer test // ' . uniqid('', true))
// Set the From address with an associative array
->setFrom(array('first.name@mail.com' => 'Me'))
// Set the To addresses with an associative array
->setTo(array('first.name@mail.com' => 'Me'));
// attach the image as attachment
$message->attach(Swift_Attachment::fromPath('./path/to/file.png')->setFilename('cool_image.png'));
// set the email's body as plain text
$message->addPart('My amazing body in plain text', 'text/plain');
// add the email's HTML part to the message
$message->addPart(
'<!doctype html>' .
'<html>' .
' <head><meta charset="UTF-8"></head>' .
' <body>' .
' Here is an image <br />'.
' <img src="' . $message->embed(Swift_Image::fromPath('./path/to/file.png')->setFilename('inline_cool_image.png')) . '" alt="Inline Image" /><br />' .
' Rest of message' .
' </body>' .
'</html>',
'text/html' // Mark the content-type as HTML
);
// send the message
if (!$mailer->send($message, $failures))
{
echo "Failures:";
print_r($failures);
}
}
Протестировано с версией SwiftMailer 5.4.4, Thunderbird 45.5.0 на macOS и веб-интерфейсом Gmail.
Попробуйте добавить ->setDisposition('inline')
к вашему Swift_Image
Swift_Image::fromPath('./path/to/file.png')->setFilename('inline_cool_image.png')->setDisposition('inline')