Using Pear Mail to send plain text and html emails (How to set "Content-Type" and use boundary properly)

Using Pear Mail to send plain text and html emails (How to set "Content-Type" and use boundary properly)

我正在尝试开发一种可以在我网站的各个部分使用的电子邮件发送功能。我希望电子邮件经过 SMTP 身份验证,所以我正在使用 Pear。

我的函数的一个参数设置为确定电子邮件应该是纯文本 html,还是两者都发送 (multipart/alternative)...

    if($set_content_type == 'text'){
        $content_type = 'text/plain';
    } elseif($set_content_type == 'html'){
        $content_type = 'text/html';
    } elseif($set_content_type == 'html_and_text'){
        $boundary = uniqid();
        $content_type = 'multipart/alternative; boundary=' . $boundary;
    }

然后我使用 Mail_mime 发送电子邮件...

    $mime = new Mail_mime();
    $mime->setHTMLBody($html);
    $mime->setTXTBody($text);
    $body = $mime->get();

    $host = "myhost";
    $port = "25"; // 8025, 587 and 25 can also be used.

    $username = "myusername";
    $password = "mypassword";

    $headers = array (
        'From' => $from,
        'To' => $to,
        'Subject' => $subject,
        'Content-Type:' => $content_type);

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

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

我的 question/problem:我可以在这段代码中的什么地方设置消息的各个部分以遵循 multipart/alternative mime 类型并正确使用边界,就像这个答案中显示的那样(Different Content Types in email)?

您必须在 $mime 对象上设置 ContentType

$mime = new Mail_mime();
$mime->setHTMLBody($html);
$mime->setTXTBody($text);
$mime->setContentType($content_type);
$body = $mime->get();

现在我建议您使用其他邮件而不是来自 pear 的邮件。 Pear 是一个有点老的数据包管理器,一些应用程序停止支持它,如 PHPUnit 和 Symfony。

最好使用另一个可以通过composer安装的。你可以看看Swiftmailer