How to Embed Images in HTML Emails Using PHPMailer?

Susan Sarandon
Release: 2024-10-23 00:43:03
Original
605 people have browsed it

How to Embed Images in HTML Emails Using PHPMailer?

How to Embed Images in HTML Email

Sending HTML emails with embedded images can be challenging. Many solutions rely on external resources, which can cause images to fail to load due to spam filters or email client restrictions.

To overcome these issues, consider using a reliable library such as PHPMailer. Let's explore how to use PHPMailer to embed images:

PHPMailer's documentation provides excellent guidance on displaying embedded (inline) images. It recommends using the AddEmbeddedImage function:

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

where:

  • filename is the path to the image file
  • cid is the Content ID used to link the image in the HTML email
  • name is the filename that will be displayed

For example:

<code class="php">$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');</code>
Copy after login

To incorporate the embedded image into the HTML email, insert an img tag with the src attribute set to the cid value:

<code class="html"><img src="cid:my-photo" alt="my-photo" /></code>
Copy after login

Here's a complete code example:

<code class="php">require_once('../class.phpmailer.php');
$mail = new PHPMailer(true);

$mail->IsSMTP();

try {
  $mail->Host       = "mail.yourdomain.com";
  $mail->Port       = 25;
  $mail->SetFrom('from@example.com', 'From Name');
  $mail->AddAddress('to@example.com', 'To Name');
  $mail->Subject = 'PHPMailer Test';

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

  $mail->Send();
} catch (phpmailerException $e) {
  echo $e->errorMessage();
} catch (Exception $e) {
  echo $e->getMessage();
}</code>
Copy after login

This code constructs the HTML email with the embedded image and sends it using SMTP. You can adapt this example to send emails in other ways or use different methods provided by PHPMailer, such as CreateBody to retrieve the message content and send it manually.

The above is the detailed content of How to Embed Images in HTML Emails Using PHPMailer?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!