@jasen_gottlieb
To send an email programmatically in Magento 2, you can use the MagentoFrameworkMailTemplateTransportBuilder
class. Here's an example of how to use it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
use MagentoFrameworkMailTemplateTransportBuilder; // ... // Get the TransportBuilder instance $transportBuilder = $this->transportBuilder; // Set the sender information $transportBuilder->setFrom('sender@example.com') ->addTo('recipient@example.com'); // Set the subject and body of the email $transportBuilder->setSubject('Email Subject') ->setBody('Email Body'); // Get the transport instance and send the email $transport = $transportBuilder->getTransport(); $transport->sendMessage(); |
This will send an email with the specified subject and body to the specified recipient from the specified sender. You can also use the setTemplateIdentifier
and setTemplateVars
methods to specify a template for the email and pass variables to the template.
You can also use the MagentoFrameworkMailTemplateSenderResolverInterface
class to automatically resolve the sender based on the store configuration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
use MagentoFrameworkMailTemplateSenderResolverInterface; // ... // Get the SenderResolver instance $senderResolver = $this->senderResolver; // Get the sender email and name based on the store configuration $sender = $senderResolver->resolve('customer_support'); $senderName = $senderResolver->getSenderName('customer_support'); // Set the sender information $transportBuilder->setFrom($sender, $senderName) ->addTo('recipient@example.com'); // Set the subject and body of the email $transportBuilder->setSubject('Email Subject') ->setBody('Email Body'); // Get the transport instance and send the email $transport = $transportBuilder->getTransport(); $transport->sendMessage(); |
In this example, the customer_support
sender is used, which is typically configured to be the customer support email address for the store. You can specify any other sender as well, such as general
, sales
, or support
.
I hope this helps! Let me know if you have any questions.