在电子邮件正文中嵌入base64图像

时间:2014-01-25 13:18:41

标签: php html email mime-types email-attachments

我正在尝试使用png图标在电子邮件正文中嵌入base64图像,但要么我得到空图像,要么我得到原始代码而不是html。我根据Stackoverflow中的其他帖子玩了不同的内容类型我认为它应该是第一个多部分/替代然后多部分/混合,但是我不确定哪个部分应该进入电子邮件的标题和什么去电子邮件正文。我无法得到任何好的教程。也许有人知道一些工具可以将普通的html文档转换成嵌入图像的文档吗?

    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type: multipart/alternative; boundary='boundary1'" . "\r\n";
    $headers .= "From: StudentOpen <web@mymail.com>" . "\r\n";
    $headers .= "Reply-To: web@mymail.com" . "\r\n";

    $subject = $GLOBALS['tpl']['win_mail_subject'];

    $emailText = '';

    $emailText .= "Content-type:multipart/mixed; boundary='boundary1'" . "\r\n";
    $emailText .= "Content-type:multipart/alternative; boundary='boundary2'" . "\r\n";

    $emailText .= '--boundry1' . "\r\n";
    $emailText .= "--boundry2" . "\r\n";
    $emailText .= "Content-Type: text/html; charset=UTF-8" . "\r\n";
    $emailText .= "Content-Transfer-Encoding: 7bit" . "\r\n";

    $emailText .= "<html>";
    $emailText .= "<head>";
    $emailText .= '<meta http-equiv="content-type" content="text/html; charset=UTF-8">';
    $emailText .= "</head>";
    $emailText .= "<body>";

    $emailText .= $GLOBALS['tpl']['howdy'].' '.$tmp_member_username.',';
    $emailText .= '<br/>';
    $emailText .= $GLOBALS['tpl']['win_mail_description1'];        

    $emailText .= '<img src="cid:facebook.png" alt="Facebook"/>';

    $emailText .= '</body>';
    $emailText .= '</html>';

    // facebook.png

    $emailText .= "--boundry2" . "\r\n";
    $emailText .= "Content-Type: image/png;" . "\r\n";
    $emailText .= "name='facebook.png'" . "\r\n";
    $emailText .= "Content-Transfer-Encoding: base64" . "\r\n";
    $emailText .= "Content-ID: <facebook.png>" . "\r\n";
    $emailText .= "Content-Disposition: inline;" . "\r\n";
    $emailText .= "filename='facebook.png'" . "\r\n";

    $emailText .= "iVBORw0KGgoAAAA...AAElFTkSuQmCC" . "\r\n"; // base64 string

    $emailText .= "--boundry2" . "\r\n";
    $emailText .= "--boundry1" . "\r\n";

    $body = $emailText;

    mail($user_email, $subject, $body, $headers);

我做错了什么?我作为电子邮件收到的消息搞砸了。从--boundry1开始,然后我得到原始文本。

1 个答案:

答案 0 :(得分:1)

您不应尝试自己创建有效的MIME电子邮件。虽然可以这样做,但使用专用库可以更容易,它可以正确实现所有边缘情况和陷阱,您需要做的就是调用几种方法来发送电子邮件。如果有变化,这也更容易维护。

本案例中提到的两个库是PHPMailerSwiftmailer。使用其中任何一个,代码如下:

(改编自Swiftmailer示例代码)

require_once 'lib/swift_required.php';

$message = Swift_Message::newInstance();

// Give the message a subject
$message->setSubject($GLOBALS['tpl']['win_mail_subject']);

// Set the From address with an associative array
$message->setFrom(array('web@mymail.com' => 'StudentOpen'));

// Set the To addresses with an associative array
$message->setTo(array($user_email));

$emailText = '<html>...omitted here ... 
    <img src="' . $message->embed(Swift_Image::fromPath('facebook.png')) . '" alt="Facebook" />
</html>';

// Give it a body
$message->setBody($emailText, 'text/html');

之后,你发送它。完成。