WooCommerce, being extensible by design, provides a robust email system, known as WooCommerce Mailer. This system allows you to send various types of emails, including transactional ones like order receipts, shipping notifications, and customer account updates.
![](https://youssefbouhlal.com/wp-content/uploads/2024/02/woocommerce-mailer.webp)
1. Sending Emails Using WooCommerce Mailer
Sending emails using WooCommerce Mailer is remarkably straightforward. With just a few lines of code, you can seamlessly integrate email functionality into your plugin.
$mailer = WC()->mailer();
$recipient = 'youbou@email.com';
$subject = __( 'This is the email subject', 'youbou_textdomain' );
$content = __( 'This is the content of the email', 'youbou_textdomain' );
$headers = "Content-Type: text/html";
$email_sent = $mailer->send( $recipient, $subject, $content, $headers );
if ( $email_sent ) {
// Email was sent
} else {
// Email was not sent
}
2. Create a custom template for the content
To utilize a custom template in the email content, you can create a dedicated template file within your plugin or theme directory. Start by designing the HTML structure of your email template, including placeholders for dynamic content if needed.
<?php
/**
* Template for my custom email.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/*
* @hooked WC_Emails::email_header() Output the email header
*/
do_action( 'woocommerce_email_header', $email_heading, $email ); ?>
<?php /* translators: %s: Customer first name */ ?>
<p><?php printf( esc_html__( 'Hi %s,', 'youbou_textdomain' ), esc_html( $customer_name ) ); ?></p>
<!-- add here any HTML content -->
<?php
/*
* @hooked WC_Emails::email_footer() Output the email footer
*/
do_action( 'woocommerce_email_footer', $email );
3. Using the custom template
Utilizing wc_get_template_html
, you can seamlessly retrieve your custom template and seamlessly integrate it into your email content. Moreover, you have the flexibility to include custom arguments, such as $customer_name
in the provided example, allowing for dynamic and personalized email compositions tailored to your specific needs.
$mailer = WC()->mailer();
$recipient = 'youbou@email.com';
$subject = __( 'This is the email subject', 'youbou_textdomain' );
$content = wc_get_template_html( 'custom-template.php', array(
'email_heading' => $subject,
'email' => $mailer,
'customer_name' => 'youssef',
), '', '/PATH_TO_YOUR_TEMPLATES_FOLDER/' );
$headers = "Content-Type: text/html";
$email_sent = $mailer->send( $recipient, $subject, $content, $headers );
if ( $email_sent ) {
// Email was sent
} else {
// Email was not sent
}