我正在尝试在电子邮件主体中嵌入带有png图标的base64图像,但是我要么得到空图像,要么我得到原始代码而不是html。我根据stackoverflow中的其他帖子进行了不同的内容类型,我认为应该是第一个多部分/替代方案,然后是多部分/混合,但是我不确定应该进入电子邮件的标题以及电子邮件主体什么部分。我对此无法获得任何好的教程。也许有人知道一些将常规HTML文档转换为带有嵌入图像的工具?
$headers = "MIME-Version: 1.0" . "rn";
$headers .= "Content-type: multipart/alternative; boundary='boundary1'" . "rn";
$headers .= "From: StudentOpen <web@mymail.com>" . "rn";
$headers .= "Reply-To: web@mymail.com" . "rn";
$subject = $GLOBALS['tpl']['win_mail_subject'];
$emailText = '';
$emailText .= "Content-type:multipart/mixed; boundary='boundary1'" . "rn";
$emailText .= "Content-type:multipart/alternative; boundary='boundary2'" . "rn";
$emailText .= '--boundry1' . "rn";
$emailText .= "--boundry2" . "rn";
$emailText .= "Content-Type: text/html; charset=UTF-8" . "rn";
$emailText .= "Content-Transfer-Encoding: 7bit" . "rn";
$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" . "rn";
$emailText .= "Content-Type: image/png;" . "rn";
$emailText .= "name='facebook.png'" . "rn";
$emailText .= "Content-Transfer-Encoding: base64" . "rn";
$emailText .= "Content-ID: <facebook.png>" . "rn";
$emailText .= "Content-Disposition: inline;" . "rn";
$emailText .= "filename='facebook.png'" . "rn";
$emailText .= "iVBORw0KGgoAAAA...AAElFTkSuQmCC" . "rn"; // base64 string
$emailText .= "--boundry2" . "rn";
$emailText .= "--boundry1" . "rn";
$body = $emailText;
mail($user_email, $subject, $body, $headers);
我做错了什么?我作为电子邮件收到的消息弄乱了。从 - 绑定1开始,然后我得到原始文本。
您不应该尝试自己创建有效的MIME电子邮件。虽然可以这样做,但是使用具有正确实现的所有边缘案例和陷阱的专用库,这会更容易,而您需要做的就是调用几种方法来发送电子邮件。如果要更改,这也更容易维护。
在这种情况下提到的两个库是phpmailer和Swiftmailer。使用其中任何一个,都使用这样的代码:
(根据Swift -Mailer示例代码进行了改编)
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');
之后,您发送了它。完成。