【问题标题】:How may I send an image into a e-mail body using SwiftMailer?如何使用 SwiftMailer 将图像发送到电子邮件正文?
【发布时间】:2019-02-13 13:25:03
【问题描述】:

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

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

我使用此功能是为了发送一封更改用户密码的电子邮件。

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】:

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

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

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

    (https://swiftmailer.symfony.com/docs/messages.html)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多