使用PHP Mailer同时发送HTML和纯文本电子邮件 [英] Send html and plain text email simultaneously with PHP Mailer

查看:93
本文介绍了使用PHP Mailer同时发送HTML和纯文本电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时通过电子邮件发送html和纯文本.我发现这个非常简单的教程,但是它使用了mail()函数发送电子邮件. 如何转换此代码以使用PHP Mailer类发送电子邮件?

I would like to send both html and plain text simultaneously in an email. I found this pretty straightforward tutorial but it used the mail() function to send the email. How do I transform this code send an email with the PHP Mailer class?

//specify the email address you are sending to, and the email subject
$email = 'email@example.com';
$subject = 'Email Subject';

//create a boundary for the email. This 
$boundary = uniqid('np');

//headers - specify your from email address and name here
//and specify the boundary for the email
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From: Your Name \r\n";
$headers .= "To: ".$email."\r\n";
$headers .= "Content-Type: multipart/alternative;boundary=" . $boundary . "\r\n";

//here is the content body
$message = "This is a MIME encoded message.";
$message .= "\r\n\r\n--" . $boundary . "\r\n";
$message .= "Content-type: text/plain;charset=utf-8\r\n\r\n";

//Plain text body
$message .= "Hello,\nThis is a text email, the text/plain version.
\n\nRegards,\nYour Name";
$message .= "\r\n\r\n--" . $boundary . "\r\n";
$message .= "Content-type: text/html;charset=utf-8\r\n\r\n";

//Html body
$message .= "
 Hello,
This is a text email, the html version.

Regards,
Your Name";
$message .= "\r\n\r\n--" . $boundary . "--";

//invoke the PHP mail function
mail('', $subject, $message, $headers);

推荐答案

请参见下文:

$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("reply@thehost.com", "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);
}

感谢 http://snippets.aktagon.com/snippets/129-how-to-send-both-html-and-text-emails-with-php-and-phpmailer 和Google. SMTP使用对您来说可能是可选的.

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.

这篇关于使用PHP Mailer同时发送HTML和纯文本电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆