Get started with 33% off your first certification using code: 33OFFNEW

How to send email from WordPress the right way (HTML and plaintext)

2 min read
Published on 23rd January 2024

Sending emails is a fundamental feature in many WordPress sites, whether it's for user registration, notifications, or custom alerts. While PHP's mail function is a common method, WordPress offers more sophisticated and reliable functions for email delivery. Let's delve into the proper ways to send both plaintext and HTML emails in WordPress.

Why Not Use PHP's mail Function?

PHP's mail function, although straightforward, often lacks versatility and reliability. It doesn't support SMTP authentication, which can lead to emails being marked as spam. WordPress's built-in functions provide better handling, formatting, and deliverability.

Sending Plaintext Emails in WordPress

For plaintext emails, WordPress provides the wp_mail() function. It's similar to PHP's mail but more powerful and flexible.

Basic Usage of wp_mail():

$to = '[email protected]';
$subject = 'Welcome to Our Website!';
$message = 'Thank you for joining our website.';

wp_mail($to, $subject, $message);

Setting Additional Headers:

To add headers, such as 'From' or 'Reply-To', use an array:

$headers = array('From: Me Myself <[email protected]>', 'Reply-To: [email protected]');
wp_mail($to, $subject, $message, $headers);

Sending HTML Emails

To send HTML emails, you need to set the content type to text/html. This can be done using the wp_mail_content_type filter.

Example:

function set_html_mail_content_type() {
    return 'text/html';
}
add_filter('wp_mail_content_type', 'set_html_mail_content_type');

$to = '[email protected]';
$subject = 'Your Account Details';
$message = '<html><body>';
$message .= '<h1>Welcome to Our Website!</h1>';
$message .= '<p>Here are your account details.</p>';
$message .= '</body></html>';

wp_mail($to, $subject, $message);

// Reset content-type to avoid conflicts
remove_filter('wp_mail_content_type', 'set_html_mail_content_type');

Best Practices for Sending Emails in WordPress

  1. Use SMTP Plugin: Consider using an SMTP plugin to improve email deliverability. Plugins like 'WP Mail SMTP' or 'Easy WP SMTP' let you use an external SMTP service.

  2. Asynchronous Sending: For sending large volumes of email, consider offloading the task to an asynchronous process or a third-party email service to avoid slowing down your site.

  3. Testing: Regularly test your email functionality, especially after updates or changes to your site.

  4. Email Templates: For HTML emails, create clean and responsive email templates. Keep the design consistent with your brand.

  5. Avoid Spam Triggers: Be mindful of the content in your emails. Avoiding spammy words, excessive links, or large images can help prevent your emails from being marked as spam.