Как отправить HTML-адрес электронной почты с помощью SMTP в PHP

Я смог отправить электронное письмо с использованием SMTP в PHP, но когда я пытаюсь изменить Content Type на HTML, письмо не доставляется. Это код, который я пытаюсь использовать:

require_once "Mail.php"; $from = "FPM <forms@fpmofames.com>"; $from_name = "FPM"; $host = "localhost"; $username = "username"; $password = "password"; $subject = "Subject"; $message = "Message"; $to = "<example@example.com>"; $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); 

Если я беру аргумент «Content-Type» из заголовков, он отправляет сообщение просто отлично. Я не знаю, почему добавление, которое вызывает проблему.

Проблема, скорее всего, заключается в классе Mail, но поскольку мы не знаем, какой класс Mail вы используете, его сложно ответить. Если вы еще не сделали этого, я бы действительно подумал об использовании PHPMailer http://phpmailer.worxware.com/

Я провел некоторое исследование, затем я сделал свой собственный код для отправки почты с форматированием HTML с использованием SMTP-аутентификации. Глянь сюда:

 <?php require_once "Mail.php"; $url = $_GET['baseUrl']; // source url $success = false; $senderName = isset( $_GET['txtname'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_GET['txtname'] ) : ""; $senderEmail = isset( $_GET['txtemail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_GET['txtemail'] ) : ""; $msg = isset( $_GET['txtDesc'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_GET['txtDesc'] ) : ""; $body = '<table width="400" border="0"> <tr> <th scope="col">Name:</th> <th scope="col">'.$senderName.'</th> </tr> <tr> <th scope="col">Company:</th> <td scope="col">'.$_GET['txtCompany'].'</td> </tr> <tr> <th scope="row">Phone:</th> <td>'.$_GET['txtphone'].'</td> </tr> <tr> <th scope="row">E-mail:</th> <td>'.$senderEmail.'</td> </tr> <tr> <th scope="row">URL:</th> <td>'.$url.'</td> </tr> <tr> <th scope="row">Massage:</th> <td>'.$msg.'</td> </tr> </table>'; $from = $senderName."<".$senderEmail.">"; $to = "Contact ManagerHR<info@aequitas-infotech.com>"; $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("<p>" . $mail->getMessage() . "</p>"); } else { header('Location: '.$url); // redirect to url where from inquiry made //echo("<p>Message successfully sent!</p>"); } ?> 

Вы должны создать тело письма через mime-объект. И груша справится с этим оттуда. Пример:

  $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(); 
 Hi developers you can complete in two steps Step 1: put code in your file <?php require 'PHPMailerAutoload.php'; $mail = new PHPMailer; //$mail->SMTPDebug = 3; // Enable verbose debug output $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'user@example.com'; // SMTP username $mail->Password = 'secret'; // SMTP password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 587; // TCP port to connect to $mail->setFrom('from@example.com', 'Mailer'); $mail->addAddress('joe@example.net', 'Joe User'); // Add a recipient $mail->addAddress('ellen@example.com'); // Name is optional $mail->addReplyTo('info@example.com', 'Information'); $mail->addCC('cc@example.com'); $mail->addBCC('bcc@example.com'); $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body <b>in bold!</b>'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'; } Step:2 Download this included file in given URL. Url: https://github.com/PHPMailer/PHPMailer.git and click on **clone or download** button and set folder your system.