I'm trying to send an image in an email body using SwiftMailer. I use SwiftMailer in order to send email for changing password, etc.
I tried to use cid method or also embed method using the SwiftMailer's documentation. Unfortunately none of these methods work. I still get no image in my email sent.
I used this function in order to sent an email for changing the password of the user.
public function sendResettingEmailMessage(UserInterface $user)
{
$template = $this->parameters['template']['resetting'];
$url = $this->router->generate('fos_user_resetting_reset', array('token' =>
$user->getConfirmationToken()), UrlGeneratorInterface::ABSOLUTE_URL);
$context = array(
'user' => $user,
'confirmationUrl' => $url,
);
$this->sendMessage($template, $context, $this->parameters['from_email']['resetting'], (string) $user->getEmail());
}
Then I use this function to create the message of the email :
protected function sendMessage($templateName, $context, $fromEmail,
$toEmail)
{
$template = $this->twig->load($templateName);
$subject = $template->renderBlock('subject', $context);
$textBody = $template->renderBlock('body_text', $context);
$htmlBody = '';
if ($template->hasBlock('body_html', $context)) {
$htmlBody = $template->renderBlock('body_html', $context);
}
$message = (new \Swift_Message())
->setSubject($subject)
->setFrom($fromEmail)
->setTo($toEmail)
->setBody(
'<html>' .
' <body>' .
' Here is an image <img src="' .
$message-
>embed(Swift_Image::fromPath('https://via.placeholder.com/350x150')) .
'" alt="Image" />' .
' Rest of message' .
' </body>' .
'</html>',
'text/html' // Mark the content-type as HTML
);
return $this->mailer->send($message);
}
Here is my email.html.twig :
{% trans_default_domain 'FOSUserBundle' %}
{% block subject %}
{%- autoescape false -%}
{{ 'registration.email.subject'|trans({'%username%': user.username,
'%confirmationUrl%': confirmationUrl}) }}
{%- endautoescape -%}
{% endblock %}
{% block body_text %}
{% autoescape false %}
{{ 'registration.email.message'|trans({'%username%': user.username,
'%confirmationUrl%': confirmationUrl}) }}
{% endautoescape %}
{% endblock %}
{% block body_html %}
{% endblock %}
I expect that in my e-mail I will get a simple placeholder inside the body. But the result is this placeholder never appeared in my email. I only have the body with the text without the image.
How may i add this placeholder inside the body of my email ?
Thank you for your replies.
According to the documentation, could you try this :
$message->attach(
Swift_Attachment::fromPath('https://via.placeholder.com/350x150')->setDisposition('inline')
)
And please check if allow_url_fopen
is set on
in your php.ini