Sometimes, when you’re working on a WordPress project with a tight deadline, you have to come up with quick and easy ways to do certain things. For example, to batch send emails to multiple users, either from a DB or from a CSV file, etc.
Instead of going the “right” path by finding some plugin that does this, or using some external SaaS solution, you may as well use the WP API itself, particularly the wp_mail()
function.
Example code:
<?php define('WP_ROOT', __DIR__); require_once WP_ROOT . '/wp-load.php'; // Load WP //Some code to get users here $emails = ['someemail@somedomain.com', 'someemail2@somedomain.com', 'someemail3@somedomain.com', 'someemail4@somedomain.com']; $headers = []; $headers[] = 'Content-Type: text/html; charset=UTF-8'; // Important header if you want to enable HTML mode of the mail. $headers[] = 'Bcc: somebccaddress@somewhere.org'; $subject = 'Very nice email subject here'; foreach ($emails as $email) { // Write your body message here in HTML $body = <<<EOD <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html data-editor-version="2" class="campaigns" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"> <style type="text/css"> body {width: 600px;margin: 0 auto;} table {border-collapse: collapse;} table, td {mso-table-lspace: 0pt;mso-table-rspace: 0pt;} img {-ms-interpolation-mode: bicubic;} </style> </head> <body> <h1>Hello from WP_MAIL() :) </h1> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde itaque beatae est sit praesentium voluptate corrupti minus officia laborum earum, repudiandae porro delectus laudantium eaque officiis provident, tenetur ad, quibusdam?</p> </body> EOD; wp_mail( $email, $subject, $body, $headers ); //Bool }
Put this file in the root of your site, for example: /send_emails.php
, and run it through the browser like so:https://mysite.com/send_emails.php.
Make sure you delete that file when you are done with the whole action, since, although minor, this file will still pose a security issue.