Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sending multiple emails using the TransportBuilder class causes an Zend_Mail exception #14236

Closed
david-kominek opened this issue Mar 21, 2018 · 26 comments
Assignees
Labels
Fixed in 2.3.x The issue has been fixed in 2.3 release line Issue: Cannot Reproduce Cannot reproduce the issue on the latest `2.4-develop` branch Issue: Clear Description Gate 2 Passed. Manual verification of the issue description passed Issue: Format is valid Gate 1 Passed. Automatic verification of issue format passed

Comments

@david-kominek
Copy link

david-kominek commented Mar 21, 2018

Preconditions

  1. Magento 2.2.3
  2. PHP 7.0.12
  3. MySQL 5.7.18

Steps to reproduce

  1. Fresh install of Magento
  2. Make a custom module with 2 observer classes on an event('sales_order_place_after'). Each of these observers should inject the TransportBuilder class and send an email:
$transport = $this->transportBuilder
    ->setTemplateIdentifier('email_template_identifier')
    ->setTemplateOptions([
        'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
        'store' => 1
    ])
    ->setTemplateVars($data)
    ->setFrom($sender)
    ->addTo($mailto);

// important that this is its own line for when we override the transport builder due to how PHP polymorphism works :(
$transport = $this->transportBuilder->getTransport();

$transport->sendMessage();
  1. Checkout and place an order.

Expected result

  1. Two emails will be sent...

Actual result

  1. The first email is sent, the second email is never sent...
  2. The second observer will throw an exception in the $transport->sendMessage() function: throw new Zend_Mail_Exception('From Header set twice');
  3. The system.log file will show the following line: "[2018-03-21 19:32:06] main.ERROR: From Header set twice [] []"

The issue seems to be that the transport builder is not adequately cleaning up the $message variable after getting the transport. The solution is to overwrite the TransportBuilder class, and in the function getTransport() to the following:

<?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="Vendor\Module\Model\Mail\TransportBuilder" />
</config>
class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{
    public function getTransport()
    {
        $mailTransport = parent::getTransport();
        $this->message->clearFrom()
            ->clearReplyTo()
            ->clearReturnPath()
            ->clearSubject()
            ->clearMessageId()
            ->clearRecipients()
            ->setParts([]);

        return $mailTransport;
    }
}

Edit: I don't feel that @dimonovp really reviewed this ticket. Can we have it reopened and reviewed?

@magento-engcom-team magento-engcom-team added the Issue: Format is valid Gate 1 Passed. Automatic verification of issue format passed label Mar 21, 2018
@magento-engcom-team
Copy link
Contributor

@david-kominek, please refer to the Community Forums or the Magento Stack Exchange site for advice or general discussion about this issue. The GitHub issue tracker is intended for Magento Core technical issues only.

@david-kominek
Copy link
Author

OK, so I'm just a little confused. The core team intended the TransportBuilder to be a single use class? The way that it currently is implemented, you can only use the TransportBuilder one time per request, no matter which class you inject it into. I thought the point of a "Builder" class was to be able to build multiple of something.

@sebastian-enz
Copy link
Contributor

@magento-engcom-team Are you sure it is appropriate to close this ticket? This seems to be a real issue. TransportBuilder should not be usable once per request only. For example, what about an extension creating 5 shipments for different orders and emailing them to customers, in "one request/execution" -- right now, using Magento\Sales\Model\Order\Email\Sender\ShipmentSender only the first of the five shipment emails would be sent, as after the first email, the above exception described by @david-kominek is stopping further emails from being sent.

@heldchen
Copy link
Contributor

we have this problem too, first noticed after updating to 2.2.4.

the TransportBuilder uses ObjectManager in reset() to create a "new" \Magento\Framework\Mail\Message instance:

    /**
     * Reset object state
     *
     * @return $this
     */
    protected function reset()
    {
        $this->message = $this->objectManager->create(\Magento\Framework\Mail\Message::class);
        $this->templateIdentifier = null;
        $this->templateVars = null;
        $this->templateOptions = null;
        return $this;
    }

once a mail was previously created, the object returned from the ObjectManager won't be a new, uniinitalized object and thus needs at least be reset properly. or get rid of the object manager stuff as everyone seems to preach nowadays.

@andypieters
Copy link

Having the same issue in 2.2.4.
Our payment plugin sends the order confirmation and invoice when the payment is completed.
The order confirmation is sent, the invoice is not.
This worked in the past and it clearly is a bug in magento core.
Iam using \Magento\Sales\Model\Order\Email\Sender\OrderSender and \Magento\Sales\Model\Order\Email\Sender\InvoiceSender to sent those emails.
After debugging, i found out that if i don't send the order confirmation, the invoice email works.
Also got the exception: "From Header set twice"

@heldchen
Copy link
Contributor

here's a core patch: bugfix--allow-more-than-one-email-being-sent.zip

please refrain from commenting the ugliness of the patch - mostly due to the stupidity of this bug. I'm sure someone can come up with a nicer solution eventually by getting rid of this dependency injection/object manager mess introduced in 2.2.4.

@andypieters
Copy link

@heldchen Thanks.
But the thing is, i myself am not using magento, i just developed a payment plugin for our clients.
I have the feeling that @dimonovp just closed this issue without even looking at it.
@magento-engcom-team Please have a look at this and re-open this issue. We know about the forums and stack exchange, but this clearly is a bug.

@henk-hypershop
Copy link

Is a bug indeed. Please re-open this issue.

@gewaechshaus
Copy link

Same here...

@vlauria
Copy link

vlauria commented Jul 11, 2018

With Magento 2.2.4 the issue is in Magento\Framework\Mail\Template\TransportBuilderByStore, after setFrom not reset header from.

Add this function:

protected function reset()
{
        $this->message = $this->objectManager->create(\Magento\Framework\Mail\Message::class);
        return $this;
 }

and replace function setFromByStore with

public function setFromByStore($from, $store)
{
        $result = $this->senderResolver->resolve($from, $store);
        $this->message->setFrom($result['email'], $result['name']);
        $this->reset();
        return $this;
}

@heldchen
Copy link
Contributor

@vlauria this will still instantiate a new message each time setFromByStore is called, and as such break multiple sending. check the zip I've added a few comments above for a working patch.

@david-kominek
Copy link
Author

@magento-engcom-team Could we have this re-reviewed or clarification added? It seems to be an actual issue with a fairly simple solution.

@vlauria
Copy link

vlauria commented Jul 12, 2018

@heldchen Magento into Magento\Framework\Mail\Template\TransportBuilder after send message instantiate a new message, like my fix.
The problem is that magento use two transport for send mail, in TransportBuilder reset message istance.
In TransportBuilderByStore no.

@ghost ghost self-assigned this Aug 2, 2018
@ghost ghost reopened this Aug 2, 2018
@ghost ghost added Issue: Clear Description Gate 2 Passed. Manual verification of the issue description passed and removed non-issue labels Aug 2, 2018
@ghost
Copy link

ghost commented Aug 2, 2018

@david-kominek, thank you for your report.
We were not able to reproduce this issue by following the steps you provided. If you'd like to update it, please reopen the issue.

@ghost ghost closed this as completed Aug 2, 2018
@heldchen
Copy link
Contributor

heldchen commented Aug 2, 2018

this is turning into a farce. the issue is reproducible with the steps in the initial ticket, but you probably ignored with 2 observer classes

@ghost
Copy link

ghost commented Aug 2, 2018

@heldchen, you can always create new issue with more obvious steps to reproduce.
default

@hostep
Copy link
Contributor

hostep commented Aug 2, 2018

Just commenting in here since I've seen other related tickets around this.
Most people in here mention Magento 2.2.4, and in 2.2.4 the Amazon Payment module got included by default, which incorrectly made the Magento\Framework\Mail\MessageInterface non-shared. There is a pending fix over here: amzn/amazon-payments-magento-2-plugin@b9e8dca

And there is also a pending PR for Magento2 which also seems to be around something very similar: #16461

Not sure if this causes the problem discussed in this thread? It seems related.
Opening post mentions Magento 2.2.3, so it might be something completely else, in that case, ignore me :)

@david-kominek
Copy link
Author

The original issue is unrelated to the email issues introduced in 2.2.4. I've already got my solution for this issue which I mentioned in the original post. Since Magento team seems unable or unwilling to reproduce, hopefully this post will help those who come across the bug. It seems like it's not going to be resolved.

@gwharton
Copy link
Contributor

gwharton commented Aug 3, 2018

@david-kominek Hopefully PR #16461 will be approved and merged soon. This will fix this issue, along with a host of other issues.

It was the fix that was introduced to fix the original email problems, that introduced this new bug. PR #16461 is an alternative fix for the original email issue, but at the same time, does not introduce the new bug that causes the multiple email issues to occur.

Hope this helps clarify.

@gwharton
Copy link
Contributor

Fixed in 2.2-develop
9a7c9e5#diff-dfb3ee5a7f863458afea75f5524cd2e5

@stephan-cream
Copy link
Contributor

stephan-cream commented Dec 17, 2018

The 'fixes' provided in all of the respective tickets/commits linked within the current issue don't actually solve the issue or address the actual issue.

I will briefly explain the issue that occurs as concise as possible.
When framework\Mail\Template\TransportBuilder is instantiated it will fetch a singleton instance of \Magento\Framework\Mail\Message, having MessageInterface $message, in the construct.
This singleton can also be used in other classes during the mail process through the use of dependency injection, the same way as it is done as shown in the __construct of the above class.

The main issue with a singleton is that any data that is set (for example the header in this case) is kept as long as a process is running.
Seeing as a cronjob is a single process the singleton's data, once set, stays filled with whatever is set on the first time within a loop throughout the entire loop.

Example:

Loop 1:
Header = NULL
Header is set to 'A'
Header = A

Loop 2:
Header = A
Error is thrown as the header is filled.

Although the suggested fix from some of the commits in this issue $this->message = $this->messageFactory->create(); might seem to be a fix, in reality you are only replacing the singleton object in the $message variable with a new instance of \Magento\Framework\Mail\Message.
Everywhere else where the singleton is used it will still use the singleton with the old data and not your newly created instance which is only available within the given class as you are not changing the singleton's instance, just the variable's object within the current class.

A singleton is not supposed to be reinstantiated in the first place, the whole purpose of a singleton is to avoid new instances.
As such a better fix would be to reset all the data within the message singleton.
Now i am unsure whether there is an easier way, but the example below would be a way on how to fix this problem. Do note i have tested this thoroughly on multiple custom cronjobs which send order mails, invoice mails and shipment mails as well as custom mails in bulk.

vendor/magento/framework/Mail/Template/TransportBuilder.php
/**
* Reset object state
*
* @return $this
*/
protected function reset()
{
$this->message->clearDate();
$this->message->clearFrom();
$this->message->clearMessageId();
$this->message->clearRecipients();
$this->message->clearReplyTo();
$this->message->clearReturnPath();
$this->message->clearSubject();
$this->message->setParts([]);
$this->templateIdentifier = null;
$this->templateVars = null;
$this->templateOptions = null;
return $this;
}

@magento-engcom-team magento-engcom-team added the Fixed in 2.3.x The issue has been fixed in 2.3 release line label Jan 7, 2019
@tuyennn
Copy link
Member

tuyennn commented Jul 17, 2019

@gwharton @magento-engcom-team I'm confusing while it's still an issue after applied the patch on backport for my 2.2.7.
I'm using a observer to send another mail after payment successfully. Even I was trying to set transportBuilder with new implementation

setFromByScope

@tuyennn tuyennn reopened this Jul 17, 2019
@ghost ghost removed their assignment Jul 17, 2019
@gwharton
Copy link
Contributor

Someone from Magento will need to pick this up and look at what needs to be done moving forward.

With respect to updating 2.2 going forward, Magento have stopped accepting fixes for the 2.2 release line now so would need to be pursued in the 2.3-develop line.

@engcom-Bravo engcom-Bravo self-assigned this Jul 19, 2019
@m2-assistant
Copy link

m2-assistant bot commented Jul 19, 2019

Hi @engcom-Bravo. Thank you for working on this issue.
In order to make sure that issue has enough information and ready for development, please read and check the following instruction: 👇

  • 1. Verify that issue has all the required information. (Preconditions, Steps to reproduce, Expected result, Actual result).

    DetailsIf the issue has a valid description, the label Issue: Format is valid will be added to the issue automatically. Please, edit issue description if needed, until label Issue: Format is valid appears.

  • 2. Verify that issue has a meaningful description and provides enough information to reproduce the issue. If the report is valid, add Issue: Clear Description label to the issue by yourself.

  • 3. Add Component: XXXXX label(s) to the ticket, indicating the components it may be related to.

  • 4. Verify that the issue is reproducible on 2.3-develop branch

    Details- Add the comment @magento give me 2.3-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.3-develop branch, please, add the label Reproduced on 2.3.x.
    - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and stop verification process here!

  • 5. Verify that the issue is reproducible on 2.2-develop branch.

    Details- Add the comment @magento give me 2.2-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.2-develop branch, please add the label Reproduced on 2.2.x

  • 6. Add label Issue: Confirmed once verification is complete.

  • 7. Make sure that automatic system confirms that report has been added to the backlog.

@engcom-Bravo engcom-Bravo added the Issue: Cannot Reproduce Cannot reproduce the issue on the latest `2.4-develop` branch label Jul 19, 2019
@engcom-Bravo
Copy link
Contributor

engcom-Bravo commented Jul 19, 2019

This issue is fixed on 2.3.x branches(i tried to reproduce on 2.3-develop).
Thank for contributing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Fixed in 2.3.x The issue has been fixed in 2.3 release line Issue: Cannot Reproduce Cannot reproduce the issue on the latest `2.4-develop` branch Issue: Clear Description Gate 2 Passed. Manual verification of the issue description passed Issue: Format is valid Gate 1 Passed. Automatic verification of issue format passed
Projects
None yet
Development

No branches or pull requests