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

Barbara Streisand
发布: 2024-10-23 00:32:02
原创
608 人浏览过

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中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!