- 🇮🇹Italy trickfun
Thank you zegenuity
Can you provide better documentation to send mail programmatically? - 🇺🇸United States freelock Seattle
Hi,
The best way to send an Easy Email programmatically is to use ECA → . Both Easy Email and ECA are in Drupal CMS, so this is getting a lot more widespread use.
On the linked issue in #7, I had started a "Scheduled Message" module to do this, but we've switched over entirely to ECA.
Three of my recent Advent Calendar posts include this:
https://www.freelock.com/advent/2024/remind-customers-abandoned-carts
https://www.freelock.com/advent/2024/automatically-track-documentation-r...
https://www.freelock.com/advent/2024/send-roster-event-attendees-staff... the gist is, create a view that collects the people you want to email. In ECA, you use a Views Query to get all of them, and send that list to a custom event (entity aware), which ECA will then call for each person on the list. From that event create a new entity of type easy_email, and the email template you want to send. You can then associate entity reference fields to your email with the views result, and use tokens in your template as appropriate.
- 🇺🇸United States zengenuity
@trickfun, you can send emails programmatically by creating an EasyEmail entity and using the email handler service to send it. Here is an example from my DrupalTutor website where I'm sending webinar reminders to students. Note that sending an email does not save it automatically. Also, note that the sendEmails() method returns an array of email entities, because it's possible it might split an email into multiple emails if there are security-related tokens in it, such as one-time-login links.
<?php $email_handler = \Drupal::service('easy_email.handler'); $email = $email_handler->createEmail([ 'type' => 'webinar_reminder', 'field_webinar' => $webinar->id(), 'field_user' => $uid, ]); $sent_emails = $email_handler->sendEmail($email); foreach ($sent_emails as $sent_email) { $sent_email->save(); } ?>
- 🇺🇸United States zengenuity
Also,
\Drupal::service('easy_email.handler')->createEmail()
is just a helper function. You can create an easy email entity using other standard methods as well.