Skip to content

Instantly share code, notes, and snippets.

@Maxdw
Last active November 19, 2015 16:48
Show Gist options
  • Save Maxdw/2d6c4763d4b283b0100c to your computer and use it in GitHub Desktop.
Save Maxdw/2d6c4763d4b283b0100c to your computer and use it in GitHub Desktop.
WordPress - Sending multipart (text/html and plain/text) email in WordPress programatically.
/**
* Sends a email in both 'text/html' and 'plain/text'.
*
* @param string|array $to
* @param string $subject
* @param string $html
* @param string $text
* @return boolean|string
* @see stackoverflow.com/questions/22507176
*/
function send_multipart_mail($to, $subject, $html, $text) {
$result = false;
global $phpmailer;
// get PHPMailer if it was not constructed yet
if(!($phpmailer instanceof PHPMailer)) {
require_once ABSPATH . WPINC . '/class-phpmailer.php';
require_once ABSPATH . WPINC . '/class-smtp.php';
$phpmailer = new PHPMailer(true);
}
$mail =& $phpmailer;
// Empty out the values that may be set
$mail->ClearAllRecipients();
$mail->ClearAttachments();
$mail->ClearCustomHeaders();
$mail->ClearReplyTos();
// sets the default 'from' name
$from_name = 'Website';
if($site_title = get_bloginfo('name')) {
$from_name = $site_title;
}
// sets the default 'from' email address
if(!isset($from_email)) {
$domain = strtolower($_SERVER['SERVER_NAME']);
if(substr($domain, 0, 4) == 'www.') {
$domain = substr($domain, 4);
}
$from_email = 'info@' . $domain;
}
// filter from email address and name
$mail->From = apply_filters('wp_mail_from', $from_email);
$mail->FromName = apply_filters('wp_mail_from_name', $from_name);
// indicate
$mail->IsHTML(true);
$mail->CharSet = "text/html; charset=UTF-8;";
$mail->WordWrap = 80;
// Sender information
$mail->From = $from_email;
$mail->FromName = $from_name;
// let plugins have their way before we do our thing
do_action_ref_array('phpmailer_init', [&$mail]);
// Recipient information
foreach((array)$to as $to_name => $to_email) {
if(is_numeric($to_name)) {
$to_name = '';
}
$mail->AddAddress($to_email, $to_name);
}
// Content information
$mail->Subject = $subject;
$mail->Body = $html;
// This automatically sets the email to multipart/alternative.
// This body can be read by mail clients that do not have HTML
$mail->AltBody = $text;
// send email
if($mail->Send()) {
$result = true;
}
else if($mail->ErrorInfo) {
$result = $mail->ErrorInfo;
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment