Send html and plain text email simultaneously with PHP Mailer

There is a function for that in PHPMailer: msgHTML()

# Minimum code to send an email:
$phpmailer = new PHPMailer();

$phpmailer->From = $from;
$phpmailer->FromName = $from_name;

$phpmailer->AddAddress( $to, $to_name );

$phpmailer->Subject = $subject;

$phpmailer->CharSet = 'UTF-8';

$phpmailer->msgHTML( $htmlMessage ); # <- right here!

# Use PHP's mail() instead of SMTP:
$phpmailer->IsMail();

$phpmailer->Send();

Create a message from an HTML string. Automatically makes modifications for inline images and backgrounds and creates a plain-text version by converting the HTML. Overwrites any existing values in $this->Body and $this->AltBody

See full function's code on Github: https://github.com/PHPMailer/PHPMailer/blob/master/class.phpmailer.php#L3299


See below:

$mail = new PHPMailer();

$mail->IsHTML(true);
$mail->CharSet = "text/html; charset=UTF-8;";
$mail->IsSMTP();

$mail->WordWrap = 80;
$mail->Host = "smtp.thehost.com"; 
$mail->SMTPAuth = false;

$mail->From = $from;
$mail->FromName = $from; // First name, last name
$mail->AddAddress($to, "First name last name");
#$mail->AddReplyTo("[email protected]", "Reply to address");

$mail->Subject =  $subject;
$mail->Body =  $htmlMessage; 
$mail->AltBody  =  $textMessage;    # This automatically sets the email to multipart/alternative. This body can be read by mail clients that do not have HTML email capability such as mutt.

if(!$mail->Send())
{
  throw new Exception("Mailer Error: " . $mail->ErrorInfo);
}

Thanks to http://snippets.aktagon.com/snippets/129-how-to-send-both-html-and-text-emails-with-php-and-phpmailer and Google. SMTP use might be optional for you.

Tags:

Php