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>
where:
For example:
<code class="php">$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');</code>
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>
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="cid:my-attach"> Here is an image!'; $mail->Send(); } catch (phpmailerException $e) { echo $e->errorMessage(); } catch (Exception $e) { echo $e->getMessage(); }</code>
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!