如何使用SwiftMailer将图像发送到电子邮件正文?

问题描述 投票:1回答:1

我正在尝试使用SwiftMailer在电子邮件正文中发送图像。我使用SwiftMailer发送电子邮件以更改密码等。

我尝试使用cid方法或使用SwiftMailer的文档嵌入方法。不幸的是,这些方法都不起作用我发送的电子邮件中仍然没有图像。

我使用此功能发送电子邮件以更改用户的密码。

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());                                        
}

然后我使用此函数来创建电子邮件的消息:

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);
}

这是我的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 %}

我希望在我的电子邮件中,我会在主体内部获得一个简单的占位符。但结果是这个占位符从未出现在我的电子邮件中。我只有身体没有图像的文字。

我怎么可以在我的电子邮件正文中添加此占位符?

谢谢您的回复。

symfony twig swiftmailer
1个回答
0
投票

根据文档,你可以试试这个:

$message->attach(
  Swift_Attachment::fromPath('https://via.placeholder.com/350x150')->setDisposition('inline')
)

请检查allow_url_fopen是否在php.ini中设置了on

(Qazxswpoi)

© www.soinside.com 2019 - 2024. All rights reserved.