How to Send Email Programmatically in WordPress

Email communication is a cornerstone of any online presence, and WordPress offers various methods to send emails programmatically. Whether you’re sending notifications, newsletters or transactional emails understanding how to handle email functionality directly from your WordPress site can enhance your engagement and streamline operations.

How to Send Email Programmatically in WordPress

1. Using the wp_mail() Function

The wp_mail() function is the core function used in WordPress to send emails. Here are various ways to use it:

a) Basic Email

$to = 'recipient@example.com';
$subject = 'Subject of the email';
$message = 'This is the body of the email.';

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

b) HTML Email

$to = 'recipient@example.com';
$subject = 'Subject of the email';
$message = '<p>This is the <strong>body</strong> of the email.</p>';
$headers = array('Content-Type: text/html; charset=UTF-8');

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

c) Email with Additional Headers

$to = 'recipient@example.com';
$subject = 'Subject of the email';
$message = 'This is the body of the email.';
$headers = array(
    'Content-Type: text/html; charset=UTF-8',
    'From: Your Name <yourname@example.com>',
    'Cc: another@example.com',
    'Bcc: hidden@example.com'
);

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

d) Email with Attachments

$to = 'recipient@example.com';
$subject = 'Subject of the email';
$message = 'This is the body of the email.';
$headers = array('Content-Type: text/html; charset=UTF-8');
$attachments = array(WP_CONTENT_DIR . '/uploads/your-file.pdf');

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

2. Configuring SMTP for Reliable Delivery

Using SMTP ensures more reliable email delivery. Here’s how to configure it:

Using a Plugin

  1. Install and Activate WP Mail SMTP
    • Go to Plugins > Add New and search for “WP Mail SMTP”.
    • Install and activate the plugin.
  2. Configure SMTP Settings
    • Go to WP Mail SMTP settings.
    • Enter your SMTP server details (SMTP host, port, username, password, encryption type).
  3. Test SMTP Settings
    • Use the test email feature provided by the plugin to verify the configuration.

Manual Configuration

Add the following code to your theme’s functions.php file or a custom plugin:

add_action('phpmailer_init', 'wpexpertguide_configure_smtp');

function wpexpertguide_configure_smtp(PHPMailer $phpmailer) {
    $phpmailer->isSMTP();
    $phpmailer->Host = 'smtp.example.com';
    $phpmailer->SMTPAuth = true;
    $phpmailer->Port = 587; // Or 465 for SSL
    $phpmailer->Username = 'your_username';
    $phpmailer->Password = 'your_password';
    $phpmailer->SMTPSecure = 'tls'; // Or 'ssl'
}

3. Leveraging Plugins for Email Handling

Using plugins can simplify email management and offer additional features. Here are a few popular options:

  • WP Mail SMTP: Configures SMTP for better deliverability.
  • Email Templates: Allows creation and management of email templates.
  • Post SMTP: Provides detailed logs and error reporting.

Example: Using WP Mail SMTP

  1. Install and Activate WP Mail SMTP
    • Follow the installation steps from the plugin directory.
  2. Configure the Plugin
    • Navigate to WP Mail SMTP settings.
    • Enter SMTP server details.
    • Save changes.
  3. Send a Test Email
    • Use the test email feature to ensure everything is set up correctly.

Tip: Loading a Template PHP File as the Email Body

To load a PHP template file as the email body follow the below steps:

Step-by-Step Guide

  1. Create a Template File
    • Create a PHP file (e.g., email-template.php) in your theme or plugin directory.
    • Add your email HTML content and PHP variables to this file.
<!-- email-template.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Email Template</title>
</head>
<body>
    <h1>Hello, <?php echo $user_name; ?>!</h1>
    <p>This is a sample email message.</p>
</body>
</html>
  1. Load the Template File in Your Email Function
    • Use the ob_start() and ob_get_clean() functions to capture the output of the template file.
function wpexpertguide_load_email_template($template_path, $variables = array()) {
    extract($variables);
    ob_start();
    include($template_path);
    return ob_get_clean();
}

$to = 'recipient@example.com';
$subject = 'Subject of the email';
$template_path = get_stylesheet_directory_uri() . '/email-template.php'; //if you are using a child theme
$variables = array('user_name' => 'wpexpertguide');

$message = wpexpertguide_load_email_template($template_path, $variables);
$headers = array('Content-Type: text/html; charset=UTF-8');

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

Explanation

  1. Create a Template File: Define the structure of your email in a separate PHP file. Use PHP to insert dynamic content.
  2. Load the Template: Create a function to load and process the template file. Use extract($variables) to make variables accessible within the template.
  3. Send the Email: Use the wp_mail() function with the processed template as the email body.

5. Testing and Troubleshooting Email Issues

Testing your email setup is crucial to ensure emails are sent correctly. Here are some steps to test and troubleshoot:

Testing

  • Send Test Emails: Use a Email logging plugin e-g WP Mail Logging or custom scripts to send test emails.
  • Check Email Logs: Review email logs if the plugin provides them.
  • Inspect Spam/Junk Folders: Sometimes emails may be marked as spam.

Troubleshooting

  • Check SMTP Configuration: Ensure all SMTP settings are correct.
  • Review Server Logs: Look for any errors in the server logs that might indicate issues.
  • Consult Hosting Provider: Sometimes hosting providers block certain ports or email functions.

Conclusion

Sending emails programmatically in WordPress is a powerful way to manage communication directly from your site. By using the wp_mail() function, configuring SMTP and loading template files you can ensure your emails are delivered reliably and professionally. Regular testing and adherence to best practices will keep your email campaigns running smoothly.

Leave a Reply

Your email address will not be published. Required fields are marked *