Register now and start sharing your code snippets.
-->

How to send both HTML and text emails with PHP and PHPMailer

PHP posted 11 months ago by christian

This is an example on how to use PHPMailer to send an HTML email. It also shows how to include a text only version of the same email for clients, such as mutt, that don’t support HTML emails.

   1  $mail = new PHPMailer();
   2  
   3  $mail->IsHTML(true);
   4  $mail->CharSet = "text/html; charset=UTF-8;";
   5  $mail->IsSMTP();
   6  
   7  $mail->WordWrap = 80;
   8  $mail->Host = "smtp.thehost.com"; 
   9  $mail->SMTPAuth = false;
  10  
  11  $mail->From = $from;
  12  $mail->FromName = $from; // First name, last name
  13  $mail->AddAddress($to, "First name last name");
  14  #$mail->AddReplyTo("reply@thehost.com", "Reply to address");
  15  
  16  $mail->Subject =  $subject;
  17  $mail->Body =  $htmlMessage; 
  18  $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.
  19  
  20  if(!$mail->Send())
  21  {
  22    throw new Exception("Mailer Error: " . $mail->ErrorInfo);
  23  }

Tagged send, email, smtp, php, phpmailer, html