Magento 2:发送带有附件的电子邮件


Answers:


19

M2并非开箱即用,但是它是zend框架中内置的功能。这是如何将此功能添加到magento中的一个很好的参考:https ://blog.bitexpert.de/blog/sending-mails-with-attachments-in-magento-2/

万一链接失效,请创建以下内容

<?php
namespace Your\CustomModule\Magento\Mail\Template;

class TransportBuilder 
    extends \Magento\Framework\Mail\Template\TransportBuilder
{
    public function addAttachment(
        $body,
        $mimeType    = Zend_Mime::TYPE_OCTETSTREAM,
        $disposition = Zend_Mime::DISPOSITION_ATTACHMENT,
        $encoding    = Zend_Mime::ENCODING_BASE64,
        $filename    = null
    ) {
        $this->message->createAttachment($body, $mimeType, $disposition, $encoding, $filename);
        return $this;
    }
}

然后添加到etc / di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="\Magento\Framework\Mail\Template\TransportBuilder"
                type="\Your\CustomModule\Magento\Mail\Template\TransportBuilder" />
</config>

现在,您可以addAttachment()在整个网站中使用。


8
我仍然想知道为什么magento TransportBuilder没有这种方法
Murtuza Zabuawala

4
我们如何在自定义电子邮件magento 2.3中附加文件?因为它的使用zendframework 2和这个答案不工作更多
马尼什Maheshwari

3
如何在Magento 2.3中发送带有附件的电子邮件?
Dhaduk Mitesh '18

@ManishMaheshwari&Mitesh您有解决方案吗?
Sameer Bhayani

1
此解决方案在Magento2.3中不再起作用。有人可以替代附件吗?
nishu

8

从Magento 2.2.7开始,上述解决方案由于\Magento\Framework\Mail\Message删除扩展而不再起作用\Zend_Mail
为了避免缺少通过传输构建器添加附件的简便方法(当前看来,该功能是此功能的正确位置),需要为TransportBuilder创建一个替代品并使用\Zend\Mime\Part

<?php
namespace Your\CustomModule\Magento\Mail\Template;

use Magento\Framework\Mail\MessageInterface;
use Magento\Framework\Mail\MessageInterfaceFactory;
use Magento\Framework\Mail\Template\FactoryInterface;
use Magento\Framework\Mail\Template\SenderResolverInterface;
use Magento\Framework\Mail\TransportInterfaceFactory;
use Magento\Framework\ObjectManagerInterface;
use Zend\Mime\Mime;
use Zend\Mime\Part as MimePart;
use Zend\Mime\PartFactory as MimePartFactory;
use Zend\Mime\Message as MimeMessage;
use Zend\Mime\MessageFactory as MimeMessageFactory;

class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{
    /** @var MimePart[] */
    private $parts = [];

    /** @var MimeMessageFactory */
    private $mimeMessageFactory;

    /** @var MimePartFactory */
    private $mimePartFactory;

    public function __construct(
        FactoryInterface $templateFactory,
        MessageInterface $message,
        SenderResolverInterface $senderResolver,
        ObjectManagerInterface $objectManager,
        TransportInterfaceFactory $mailTransportFactory,
        MimePartFactory $mimePartFactory,
        MimeMessageFactory $mimeMessageFactory,
        MessageInterfaceFactory $messageFactory = null
    ) {
        parent::__construct(
            $templateFactory,
            $message,
            $senderResolver,
            $objectManager,
            $mailTransportFactory,
            $messageFactory
        );

        $this->mimePartFactory    = $mimePartFactory;
        $this->mimeMessageFactory = $mimeMessageFactory;
    }

    protected function prepareMessage()
    {
        parent::prepareMessage();

        $mimeMessage = $this->getMimeMessage($this->message);

        foreach ($this->parts as $part) {
            $mimeMessage->addPart($part);
        }

        $this->message->setBody($mimeMessage);

        return $this;
    }

    public function addAttachment(
        $body,
        $mimeType = Mime::TYPE_OCTETSTREAM,
        $disposition = Mime::DISPOSITION_ATTACHMENT,
        $encoding = Mime::ENCODING_BASE64,
        $filename = null
    ) {
        $this->parts[] = $this->createMimePart($body, $mimeType, $disposition, $encoding, $filename);
        return $this;
    }

    private function createMimePart(
        $content,
        $type = Mime::TYPE_OCTETSTREAM,
        $disposition = Mime::DISPOSITION_ATTACHMENT,
        $encoding = Mime::ENCODING_BASE64,
        $filename = null
    ) {
        /** @var MimePart $mimePart */
        $mimePart = $this->mimePartFactory->create(['content' => $content]);
        $mimePart->setType($type);
        $mimePart->setDisposition($disposition);
        $mimePart->setEncoding($encoding);

        if ($filename) {
            $mimePart->setFileName($filename);
        }

        return $mimePart;
    }

    private function getMimeMessage(MessageInterface $message)
    {
        $body = $message->getBody();

        if ($body instanceof MimeMessage) {
            return $body;
        }

        /** @var MimeMessage $mimeMessage */
        $mimeMessage = $this->mimeMessageFactory->create();

        if ($body) {
            $mimePart = $this->createMimePart((string)$body, Mime::TYPE_TEXT, Mime::DISPOSITION_INLINE);
            $mimeMessage->setParts([$mimePart]);
        }

        return $mimeMessage;
    }
}

别忘了替换原来的 \Magento\Framework\Mail\Template\TransportBuilder实现di.xml

请注意,此实现可能会随即将发布的Magento中断,因为 \Magento\Framework\Mail\MessageInterface::setBody()弃用,因此可能会很快删除。

高温超导


嗨!您的代码中有一个方法addAttachment,但是在哪里调用它们?我没看到
尼古拉·西林

谢谢!我添加了循环到prepareMessage方法,并且一切正常。
Nikolai Silin

@NikolaiSilin如何发送png或其他文件。
sumeet bajaj,

1

Magento 2来自Module的自定义电子邮件,不提供图片附件。

如果要在Magento 2中将图像附件与电子邮件模板一起使用,则需要重写Magento \ Framework \ Mail \ Template \ TransportBuilder类

Magento开箱即用不提供电子邮件的附件功能。您可以参考博客以获取发送图像附件的详细信息,

您需要按照以下方式添加逻辑,

 public function addAttachment(
        $body,
        $mimeType    = \Zend_Mime::TYPE_OCTETSTREAM,
        $disposition = \Zend_Mime::DISPOSITION_ATTACHMENT,
        $encoding    = \Zend_Mime::ENCODING_BASE64,
        $filename    = null
    ) {
        $this->message->createAttachment($body, $mimeType, $disposition, $encoding, $filename);
        return $this;
    }

1
您可以帮助在magento 2.3中实现相同功能吗?
Sameer Bhayani

以这种方式创建附件,直到2.2.7。2.2.8和2.3及更高版本不工作
马蒂亚斯·克莱恩

我刚刚发布了2.3.x的答案@MatthiasKleine
domdambrogia

您好,如果我有base64编码字符串,如何附加?
Ketan Borada

1

这是在magetno 2.3中通过电子邮件发送pdf的完美答案

$transport = $_transportBuilder->setTemplateIdentifier(20)
    ->setTemplateOptions($templateOptions)                                                 
    ->setTemplateVars($templateVars)
    ->setFrom($from)
    ->addTo($vendor_email)
    ->getTransport();

$html = $transport->getMessage()>getBody()->generateMessage();            
$bodyMessage = new \Zend\Mime\Part($html);
$bodyMessage->type = 'text/html';
$attachment = $_transportBuilder->addAttachment($pdfData,$fileName);      
$bodyPart = new \Zend\Mime\Message();
$bodyPart->setParts(array($bodyMessage,$attachment));
$transport->getMessage()->setBody($bodyPart);                
$transport->sendMessage();
$inlineTranslation->resume();

嗨,它引发了致命错误:未捕获的错误:在null上调用成员函数generateMessage()
gajjala sandeep

您正在创建一条新消息,当传输中已有一条消息时,这是不必要的。为什么不只是将零件添加到位?这是混乱且难以遵循的。更不用说您将解决此问题所需的工作和内存加倍。
domdambrogia

1

Magento 2.3.x兼容:

这是我对Magento 2.3的回答,因为这是google上的头号问题,并且评论中似乎有很多人在找。

在其他文章中似乎有很多关于TransportBuilder通过覆盖默认类的需求etc/di.xml,但是我正在使用的模块太小,以至于我不希望它负责默认类TransportBuilder所以我建立了一个Helper类(应该可能是基于其与已声明的电子邮件模板的耦合程度的模型-但我离题了)。

TransportBuilder没有对公众访问TransportInterface,而是生成一个克隆每次然后重置建设者。我发现构建TransportInterface实例然后将附件Part对象附加到传输的消息上更加容易。如果确实有必要TransportBuilder通过依赖项注入首选项覆盖默认值,请注意更新公共方法。记住保持代码SOLID时要练习O

namespace Vendor\Module\Helper;

use Magento\Framework\App\Area;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\DataObject;
use Magento\Framework\Filesystem\Io\File;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Mail\TransportInterface;
use Magento\Store\Model\StoreManagerInterface;
use Zend_Mime;
use Zend\Mime\Part;

/**
 * This was initially built out to send a single email. Abstract this as you 
 * wish.
 *
 * @package Vendor\Module\Helper
 */
class Mail extends AbstractHelper
{
    /**
     * @var Context
     */
    protected $context;

    /**
     * @var TransportBuilder
     */
    protected $transportBuilder;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var Config
     */
    protected $config;

    /**
     * Mail constructor.
     *
     * @param Context $context
     * @param TransportBuilder $transportBuilder
     * @param StoreManagerInterface $storeManager
     * @param Config $config
     * @param File $file
     */
    public function __construct(
        Context $context,
        TransportBuilder $transportBuilder,
        StoreManagerInterface $storeManager,
        Config $config,
        File $file
    ) {
        parent::__construct($context);
        $this->transportBuilder = $transportBuilder;
        $this->storeManager = $storeManager;
        $this->config = $config;
        $this->file = $file;
    }

    /**
     * Send the email for a Help Center submission.
     *
     * @param DataObject $templateParams
     * @param array $attachments
     * @return void
     */
    public function send(DataObject $templateParams, array $attachments = [])
    {
        $storeId = $this->storeManager->getStore()->getId();

        // Build transport
        /** @var \Magento\Framework\Mail\TransportInterface $transport */
        $transport = $this->transportBuilder
            ->setTemplateOptions(['area' => Area::AREA_FRONTEND, 'store' => $storeId])
            ->setTemplateIdentifier($this->config->getEmailTemplate())
            ->setTemplateVars($templateParams->toArray())
            ->setFrom($this->config->getEmailSender())
            ->addTo($this->config->getEmailRecipient(), 'Help Center')
            /**
             * Something important to note is that when the getTransport()
             * function is run, the message is compiled and then the builder 
             * class resets (as of 2.3.1). 
             * 
             * This is note worthy because if you want to send > 1 attachment,
             * your $builder will be reset -- losing all of the ->set* functions
             * you just used above as well as your attachment.
             * 
             * Since we append attachments to the transport, it's easier to:
             * build -> attach -> send. And this way multiple attachments 
             * can be included. :thumbsup:
             */
            ->getTransport();

        // Attach Images to transport
        foreach ($attachments as $a) {
            $transport = $this->addAttachment($transport, $a);
        }

        // Send transport
        $transport->sendMessage();
    }

    /**
     * Add an attachment to the message inside the transport builder.
     *
     * @param TransportInterface $transportBuilder
     * @param array $file Sanitized index from $_FILES
     * @return TransportInterface
     */
    protected function addAttachment(TransportInterface $transport, array $file): TransportInterface
    {
        $part = $this->createAttachment($file);
        $transport->getMessage()->addPart($part);

        return $transport;
    }

    /**
     * Create an zend mime part that is an attachment to attach to the email.
     * 
     * This was my usecase, you'll need to edit this to your own needs.
     *
     * @param array $file Sanitized index from $_FILES
     * @return Part
     */
    protected function createAttachment(array $file): Part
    {
        $ext =  '.' . explode('/', $file['type'])[1];
        $fileName = md5(uniqid(microtime()), true) . $ext;

        $attachment = new Part($this->file->read($file['tmp_name']));
        $attachment->disposition = Zend_Mime::TYPE_OCTETSTREAM;
        $attachment->encoding = Zend_Mime::ENCODING_BASE64;
        $attachment->filename = $fileName;

        return $attachment;
    }
}

我无法使其正常工作,我总是会收到一个异常消息:“未捕获的错误:在字符串上调用成员函数addPart()” ...对此有任何想法吗?:/
hallleron

1
@hallleron奇怪的是,这与我得到的有所不同,但看起来您是正确的。该MessageInterface::getBody方法的签名显示一个字符串返回类型。您可能需要深入研究TransportInterface对象,但是我可以告诉您该addPart方法存在于Zend\Mime\Message对象上。由于magento可能将该课程扩展为自己的Message课程,因此我认为尝试这样做很明智$transport->getMessage()->addpart($part);
domdambrogia

0

如先前的回答所述,magento2没有开箱即用的功能来发送带有附件的邮件。

我不知道这是否是最佳做法,但是您可以直接调用Zend_Mailclass来做到这一点,而无需创建自定义函数和override Magento\Framework\Mail\Template\TransportBuilder,如下所示

$mail = new \Zend_Mail('utf-8');
$mail->setFrom($senderEmail);
$mail->addTo($receiverEmail);
$mail->setSubject($subject);
$mail->setBodyHtml($text);

$content = file_get_contents($attachmentAbsolutePath);

$attachment = new \Zend_Mime_Part($content);
$attachment->type = 'text/xml'; // attachment's mime type
$attachment->disposition = \Zend_Mime::DISPOSITION_ATTACHMENT;
$attachment->encoding = \Zend_Mime::ENCODING_BASE64;
$attachment->filename = $filename;
$mail->addAttachment($attachment);
$mail->send();

在给出-1之前,建议使用此注释文本区域,这样每个人都可以理解出什么问题了,谢谢
LucScu

$ transport-> getMessage()-> setBody($ bodyPart);
imtiazau

得到这个未捕获的错误:调用未定义的方法Magento \\ Framework \\ Mail \\ EmailMessage :: setBody()
imtiazau

这些评论与答案无关
LucScu

我在magento 2.3.3中收到此错误
imtiazau
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.