首页  >  文章  >  后端开发  >  如何使用 PHPMailer 在 HTML 电子邮件中嵌入图像?

如何使用 PHPMailer 在 HTML 电子邮件中嵌入图像?

Barbara Streisand
Barbara Streisand原创
2024-10-23 00:32:02609浏览

How to Embed Images in HTML Email with PHPMailer?

在 HTML 电子邮件中嵌入图像:综合解决方案

发送嵌入图像的 HTML 电子邮件可以增强用户参与度并提供更具视觉吸引力的体验。然而,实现这一目标可能会带来一定的挑战。

为了简化此过程,强烈建议使用 PHPMailer 这样的库。 PHPMailer 可自动处理与电子邮件发送相关的许多常见问题,并提供对内联图像附件的支持。

使用 PHPMailer 嵌入图像

PHPMailer 提供了将嵌入图像添加到 HTML 的直观功能emails:

<code class="php">$mail->AddEmbeddedImage(filename, cid, name);</code>

例如,要嵌入名为“rocks.png”且 CID“my-attach”的图像,请使用以下代码:

<code class="php">$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");</code>

完整的 HTML 电子邮件示例

以下是如何使用 PHPMailer 发送带有嵌入图像的 HTML 电子邮件的完整示例:

<code class="php">require_once('../class.phpmailer.php');

$mail = new PHPMailer(true);
$mail->IsSMTP();

try {
  // SMTP server settings
  $mail->Host = "mail.yourdomain.com";
  $mail->Port = 25;

  // Sender and recipient information
  $mail->SetFrom('[email protected]', 'First Last');
  $mail->AddAddress('[email protected]', 'John Doe');

  // Email subject and embedded image
  $mail->Subject = 'PHPMailer Test';
  $mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");

  // HTML body with embedded image
  $mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src=&quot;cid:my-attach&quot;> Here is an image!';

  // Send the email
  $mail->Send();
  echo "Message Sent OK<p></p>\n&quot;;
} catch (phpmailerException $e) {
  echo $e->errorMessage();
} catch (Exception $e) {
  echo $e->getMessage();
}</code>

使用 PHPMailer 自定义电子邮件发送

虽然 PHPMailer 默认支持通过 SMTP 发送电子邮件,但它提供了自定义发送过程的灵活性。如果您更喜欢其他电子邮件发送方法,您仍然可以使用 PHPMailer 撰写电子邮件并使用其功能,包括嵌入式图像处理。

<code class="php">// Retrieve the message content
$mime_message = $mail->CreateBody();

// Send the email using your preferred custom method
echo $mime_message; // Echo it to the screen or send it using whatever method you want</code>

以上是如何使用 PHPMailer 在 HTML 电子邮件中嵌入图像?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn