如何在 PHP 中使用 SMTP 发送 HTML 电子邮件

发布于 2024-12-10 09:53:36 字数 1126 浏览 0 评论 0原文

我已经能够在 PHP 中使用 SMTP 发送电子邮件,但是当我尝试将内容类型更改为 HTML 时,电子邮件未送达。这是我尝试使用的代码:

    require_once "Mail.php";

    $from = "FPM <[email protected]>";
    $from_name = "FPM";

    $host = "localhost";
    $username = "username";
    $password = "password";

    $subject = "Subject";
    $message = "Message";

    $to = "<[email protected]>";
    $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”参数,它就会很好地发送消息。我不知道为什么添加它会导致问题。

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 <[email protected]>";
    $from_name = "FPM";

    $host = "localhost";
    $username = "username";
    $password = "password";

    $subject = "Subject";
    $message = "Message";

    $to = "<[email protected]>";
    $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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

童话 2024-12-17 09:53:36

我做了一些研究,然后编写了自己的代码,使用 SMTP 身份验证发送 HTML 格式的邮件。参见这里:

<?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<[email protected]>";
 $subject = "Hi!";
 $host = "XXX.host.com";
 $username = "[email protected]";
 $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>");
  }
 ?>

I did some research, then I made my own code to send mail with HTML formatting using SMTP authentication. See here:

<?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<[email protected]>";
 $subject = "Hi!";
 $host = "XXX.host.com";
 $username = "[email protected]";
 $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>");
  }
 ?>
客…行舟 2024-12-17 09:53:36

问题很可能出在 Mail 类上,但由于我们不知道您正在使用什么 Mail 类,因此很难回答。如果您还没有这样做,我真的会考虑使用 PHPMailer: https://github.com/ PHPMailer/PHPMailer

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

笑咖 2024-12-17 09:53:36

您应该通过 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();

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();
何处潇湘 2024-12-17 09:53:36

使用 PHP 中的 SMTP 将 HTML 电子邮件发送到 2 或 3 个不同的电子邮件
工作100%

<?php

require_once "Mail.php";

$host = "ssl://smtp.gmail.com";
$username = "[email protected]";
$password = "password";
$port = "465";

$to  = '[email protected]' . ', '; 
$to  = '[email protected]' . ', '; 
$to  = '[email protected]' . ', '; 

$email_from = "[email protected]";
$email_subject = "Your Subject";

$email_body = "**<html> <body>**"; 
$email_body .= "<strong> Your HTML code </strong>";
$email_body .= "**</body></html>**";


$headers = array ('From' => $email_from, 'To' => $to, 'Subject' => 
$email_subject, 'Reply-To' => $email_address , 'MIME-Version' => '1.0', 'Content-Type' => "text/html; charset=ISO-8859-1");

$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));

$mail = $smtp->send($to, $headers, $email_body);

?>

Send your HTML email using SMTP in PHP to 2 or 3 different emails
WORKING 100%

<?php

require_once "Mail.php";

$host = "ssl://smtp.gmail.com";
$username = "[email protected]";
$password = "password";
$port = "465";

$to  = '[email protected]' . ', '; 
$to  = '[email protected]' . ', '; 
$to  = '[email protected]' . ', '; 

$email_from = "[email protected]";
$email_subject = "Your Subject";

$email_body = "**<html> <body>**"; 
$email_body .= "<strong> Your HTML code </strong>";
$email_body .= "**</body></html>**";


$headers = array ('From' => $email_from, 'To' => $to, 'Subject' => 
$email_subject, 'Reply-To' => $email_address , 'MIME-Version' => '1.0', 'Content-Type' => "text/html; charset=ISO-8859-1");

$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));

$mail = $smtp->send($to, $headers, $email_body);

?>
灯下孤影 2024-12-17 09:53:36

在标题的第一行中写入内容类型,就像这样

$to = "<[email protected]>"; $headers = array ('Content-Type' => "text/html; charset=ISO-8859-1", 'From' => $from, 'To' => $to, 'Subject' => $subject, 'MIME-Version' => '1.0' ); 

这对我有用..

Write content type in a first line of header just like this

$to = "<[email protected]>"; $headers = array ('Content-Type' => "text/html; charset=ISO-8859-1", 'From' => $from, 'To' => $to, 'Subject' => $subject, 'MIME-Version' => '1.0' ); 

This is working for me..

妄断弥空 2024-12-17 09:53:36

您可以分两步完成。

第 1 步:将代码放入您的文件中:

<?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 = '[email protected]';                 // 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('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
$mail->addAddress('[email protected]');               // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');

$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';
}

第 2 步:在给定的 URL 中下载此包含的文件。
网址: https://github.com/PHPMailer/PHPMailer.git

并单击 克隆或下载按钮
并设置您的系统文件夹。

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 = '[email protected]';                 // 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('[email protected]', 'Mailer');
$mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
$mail->addAddress('[email protected]');               // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');

$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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文