php - 如何在html电子邮件中嵌入图像

标签 php html image email

我正在尝试实现一个代码来发送带有嵌入图像的 HTML 电子邮件。

我已经尝试过使用带图片的简单 HTML 电子邮件,但这张图片是从服务器获取的。

最佳答案

我强烈推荐使用像 PHPMailer 这样的库。发送电子邮件。
它更容易并自动为您处理大部分问题。

关于显示嵌入(内嵌)图像,这里是 their documentation 上的内容:

Inline Attachments

There is an additional way to add an attachment. If you want to make a HTML e-mail with images incorporated into the desk, it's necessary to attach the image and then link the tag to it. For example, if you add an image as inline attachment with the CID my-photo, you would access it within the HTML e-mail with <img src="cid:my-photo" alt="my-photo" />.

In detail, here is the function to add an inline attachment:

$mail->AddEmbeddedImage(filename, cid, name);
//By using this function with this example's value above, results in this code:
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');

给你一个更完整的例子来说明它是如何工作的:

<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on     errors, which we need to catch

$mail->IsSMTP(); // telling the class to use SMTP

try {
  $mail->Host       = "mail.yourdomain.com"; // SMTP server
  $mail->Port       = 25;                    // set the SMTP port
  $mail->SetFrom('name@yourdomain.com', 'First Last');
  $mail->AddAddress('whoto@otherdomain.com', 'John Doe');
  $mail->Subject = 'PHPMailer Test';

  $mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
  $mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';

  $mail->AddAttachment('something.zip'); // this is a regular attachment (Not inline)
  $mail->Send();
  echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}
?>

编辑:

关于您的评论,您询问了如何发送带有嵌入图像的 HTML 电子邮件,所以我给了您一个示例来说明如何做到这一点。
我告诉你的库可以使用 SMTP 以外的很多方法发送电子邮件。
看看PHPMailer Example page其他例子。

无论哪种方式,如果您不想以库支持的方式发送电子邮件,您可以(应该)仍然使用库来构建消息,然后按照您想要的方式发送。

例如:

您可以替换发送电子邮件的行:

$mail->Send();

有了这个:

$mime_message = $mail->CreateBody(); //Retrieve the message content
echo $mime_message; // Echo it to the screen or send it using whatever method you want

希望对您有所帮助。 如果您在使用它时遇到问题,请告诉我。

关于php - 如何在html电子邮件中嵌入图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1851728/

相关文章:

带有数字键的 PHP array_merge

android - 适用于平板电脑的 html5 应用程序 : possible to load images from device's filesystem?

php - Mamp localhost 解析速度非常慢

PHP Composer PSR-4 自动加载和子命名空间,未找到类

html - CSS:调整窗口大小时不会出现垂直滚动条,position:absolute

html - XPath查找其第一个子节点包含特定值的节点

html - 变换 : translate Not working across all browsers

image - 如何在 Google App Engine 中批量上传图像 BLOB?

algorithm - 图像的子图像查找和替换

php - 在多个段落中搜索多词短语(PHP/MySQL)