On this page
Sending an Email
This documentation needs review. See "Help improve this page" in the sidebar.
If you are developing new code, then you can use the new mailer API directly.
2.x
Each module that sends emails contains a Mailer service which defines an interface. As an example, we will show how to send a password recovery email to a user, using UserMailerInterface.
// **NOT YET TESTED**
$ok = Drupal::service(UserMailerInterface::class)->notify('password_reset', $user);
We can adjust the email using a callback function:
// **NOT YET TESTED**
$ok = Drupal::service(UserMailerInterface::class)
->addCallback(function (EmailInterface $email) {
$email->setSubject('New subject');
})
->notify('password_reset', $user);
1.x
Existing Email Builder
As an example, we will show how to send a password recovery email to a user. Look at the code for UserEmailBuilder, and note 3 things:
- The 'id' from the @EmailBuilder annotation.
- The 'sub_types' from the @EmailBuilder annotation.
- The parameters from the
createParams()function, ignoring the first.
These 3 show us the parameters needed to send the email
// **NOT YET TESTED**
$email_factory = Drupal::service('email_factory');
$email = $email_factory->sendTypedEmail('user', 'password_reset', $user);
if ($error = $email->getError()) {
// @todo
}New Email Builder
This case is basically the same as above, except that first we need to write an EmailBuilder, see docs.
Overriding the email
It's possible to override the email when sending. Note this is less recommended, as it's generally better to let the Email Builder build the email.
// **NOT YET TESTED**
$email_factory = Drupal::service('email_factory');
$email = $email_factory->newTypedEmail('mymodule', 'mytype')
->setSubject('Hello')
->setTo($to)
->setBody(['#markup' => 'Look at <b>me</b>'])
->send();
if ($error = $email->getError()) {
// @todo
}Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion