Send email through wp_mail
Goal: send email from your plugin through WordPress’s wp_mail(), either as framework Mail messages or from PHP templates in your plugin, with the active theme as a fallback.
Prerequisites:
- A plugin with a kernel and a container (Getting started).
- A site that can deliver mail.
wp_mail()uses PHPmail()unless an SMTP plugin or aphpmailer_inithook configures another transport.
| Class | Use it for |
|---|---|
Mail\WpMailer |
sending a framework Mail through the framework’s MailerInterface |
Mail\EmailSender |
rendering a PHP template from your plugin or the active theme and sending it |
Mail\EmailTemplate |
rendering one template file yourself |
1. Send framework messages with WpMailer
Bind WpMailer as the framework mailer in buildContainer():
use Middag\Framework\Mail\Contract\MailerInterface;
use Middag\WordPress\Mail\WpMailer;
$builder->register(MailerInterface::class, WpMailer::class)->setPublic(true);Your services depend on MailerInterface only:
<?php
declare(strict_types=1);
namespace Acme\Notes\Mail;
use Middag\Framework\Mail\Contract\MailerInterface;
use Middag\Framework\Mail\Mail;
final class NoteMailer
{
public function __construct(
private readonly MailerInterface $mailer,
) {}
public function sendReminder(string $to, string $title): void
{
$this->mailer->send(new Mail(
to: [$to],
subject: 'Reminder: ' . $title,
body: "Your note \"{$title}\" is still open.",
htmlBody: '<p>Your note <strong>' . esc_html($title) . '</strong> is still open.</p>',
replyTo: 'Acme Support <[email protected]>',
));
}
}How WpMailer maps a Mail onto wp_mail():
Mail |
wp_mail() |
|---|---|
to |
the recipient list |
subject |
the subject |
htmlBody when set, else body |
the message; an HTML body adds Content-Type: text/html; charset=UTF-8 |
from, replyTo, cc, bcc |
From:, Reply-To:, Cc: and Bcc: headers |
attachments |
the file paths |
send() throws MiddagInfrastructureException when wp_mail() returns false.
2. Send templated email with EmailSender
Bind EmailSender with your component context, so it finds the templates in your plugin:
use Middag\Framework\Kernel\Contract\HostComponentContextInterface;
use Middag\WordPress\Mail\EmailSender;
use Symfony\Component\DependencyInjection\Reference;
$builder->register(EmailSender::class)
->setArguments(['$context' => new Reference(HostComponentContextInterface::class)])
->setPublic(true);Write the template as templates/emails/note-digest.php in your plugin. The template receives the data you pass as $view, and nothing else:
<?php
/** @var array{name: string, count: int} $view */
?>
<p>Hello <?php echo esc_html($view['name']); ?>,</p>
<p>You have <?php echo (int) $view['count']; ?> open notes.</p>Send it:
$sent = $sender->send('[email protected]', 'Your digest', 'note-digest', ['name' => 'Joe', 'count' => 3]);send($to, $subject, $templateName, $data = [], $headers = [], $attachments = [])sends HTML and returnswp_mail()’s result. It returnsfalse, and logsTemplate not found, when no template matches.- The template is looked up in
{basePath}/templates/emails/{name}.phpof yourWpComponentContext, then intemplates/emails/{name}.phpof the active theme, so a theme can only add templates your plugin does not ship. sendRaw($to, $subject, $body, $isHtml = true)sends a body you built yourself; passfalsefor plain text.sendBulk($recipients, $subject, $templateName, $data)sends one message per recipient and returns[email => bool].
What can go wrong
wp_mail() cannot embed "cid:..." parts.WpMailerthrowsMiddagInfrastructureExceptionfor anAttachment::embedded()part. Attach the file normally, or use a transport that supports inline parts.wp_mail() failed to send "..." to ....wp_mail()returnedfalse. Hookwp_mail_failedto read theWP_Errorwith PHPMailer’s reason.- The plain-text body is missing. When a
Mailhas anhtmlBody,WpMailersends only the HTML.wp_mail()does not build a multipart message. - Every later email has the same sender.
EmailSender::withFrom($email, $name)addswp_mail_fromandwp_mail_from_namefilters for the rest of the request, for every plugin. Prefer aFrom:header in$headers, orMail::$from. - A template variable is undefined. Templates see only
$view. Read$view['name'], not$name. - A template error leaves an empty email. When the template throws,
EmailTemplatelogs the error and renders an empty string, andsend()still sends it. Test templates with the data you pass.
Reference
- Bridges are native first:
WpMailerand the template lookup. - Configuration & Identity: the
basePath()thatEmailSenderreads.