How to send an HTML email using SMTP in PHP
I’ve been able to send an email using SMTP in PHP, but when I try to change the Content Type to HTML, the email doesn’t get delivered. This is the code I’m trying to use:
require_once "Mail.php"; $from = "FPM "; $from_name = "FPM"; $host = "localhost"; $username = "username"; $password = "password"; $subject = "Subject"; $message = "Message"; $to = ""; $headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject, 'MIME-Version' => '1.0', 'Content-Type' => "text/html; charset=ISO-8859-1" ); $smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true, 'username' => $username, 'password' => $password)); $mail = $smtp->send($to, $headers, $message);
If I take the ‘Content-Type’ argument out of the headers, it sends the message just fine. I don’t know why adding that causes a problem.
6 Answers 6
I did some research, then I made my own code to send mail with HTML formatting using SMTP authentication. See here:
Name: '.$senderName.' Company: '.$_GET['txtCompany'].' Phone: '.$_GET['txtphone'].' E-mail: '.$senderEmail.' URL: '.$url.' Massage: '.$msg.' '; $from = $senderName.""; $to = "Contact ManagerHR"; $subject = "Hi!"; $host = "XXX.host.com"; $username = "username@host.com"; $password = "*****"; /* MIME-Version should be "1.0rn" and Content-Type should be "text/html; charset=ISO-8859-1rn" to send an HTML Email */ $headers = array ('MIME-Version' => '1.0rn', 'Content-Type' => "text/html; charset=ISO-8859-1rn", 'From' => $from, 'To' => $to, 'Subject' => $subject ); $smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true, 'username' => $username, 'password' => $password)); $mail = $smtp->send($to, $headers, $body); if (PEAR::isError($mail)) < echo("" . $mail->getMessage() . "
"); > else < header('Location: '.$url); // redirect to url where from inquiry made //echo("Message successfully sent!
"); > ?>
The problem most likely lies in the Mail class, but since we don’t know what Mail class you’re using, it’s difficult to answer. If you’re not already doing so, I’d really think about using PHPMailer: https://github.com/PHPMailer/PHPMailer
You should create the mail body via mime object. And pear will handle it from there. Ex:
$crlf = "\n"; // Creating the Mime message $mime = new Mail_mime($crlf); // Setting the body of the email $mime->setTXTBody($text); $mime->setHTMLBody($html); . $body = $mime->get();
Send your HTML email using SMTP in PHP to 2 or 3 different emails WORKING 100%
**"; $email_body .= " Your HTML code "; $email_body .= "**