Display inline image attachments with wp_mail Display inline image attachments with wp_mail wordpress wordpress

Display inline image attachments with wp_mail


wp_mail uses the PHPMailer class. This class has all the functionality needed for inline attachments.To change the phpmailer object before wp_mail() sends the email you could use the filter phpmailer_init.

$body = 'Hello John,checkout my new cool picture.<img src="cid:my-cool-picture-uid" width="300" height="400">Thanks, hope you like it ;)';

That was an example of how to insert the picture in you email body.

$file = '/path/to/file.jpg'; //phpmailer will load this file$uid = 'my-cool-picture-uid'; //will map it to this UID$name = 'file.jpg'; //this will be the file name for the attachmentglobal $phpmailer;add_action( 'phpmailer_init', function(&$phpmailer)use($file,$uid,$name){    $phpmailer->SMTPKeepAlive = true;    $phpmailer->AddEmbeddedImage($file, $uid, $name);});//now just call wp_mail()wp_mail('test@example.com','Hi John',$body);

That's all.


If you get an unexpected T_FUNCTION error, it is due to the PHP version < 5.3. In that case, create a function to do it in a more traditional way:

function attachInlineImage() {    global $phpmailer;    $file = '/path/to/file.jpg'; //phpmailer will load this file    $uid = 'my-cool-picture-uid'; //will map it to this UID    $name = 'file.jpg'; //this will be the file name for the attachment    if (is_file($file)) {      $phpmailer->AddEmbeddedImage($file, $uid, $name);    }  }  add_action('phpmailer_init','attachInlineImage');  


I needed this in a small better way because I'm sending multiple mails in one step and not all mails should have the same embedded images. So I'm using this solution from Constantin but with my Modifications :-)

wp_mail('test@example.org', 'First mail without attachments', 'Test 1');$phpmailerInitAction = function(&$phpmailer) {    $phpmailer->AddEmbeddedImage(__DIR__ . '/img/header.jpg', 'header');    $phpmailer->AddEmbeddedImage(__DIR__ . '/img/footer.png', 'footer');};add_action('phpmailer_init', $phpmailerInitAction);wp_mail('test@example.org', 'Mail with embedded images', 'Example <img src="cid:header" /><br /><img src="cid:footer" />', [    'Content-Type: text/html; charset=UTF-8'], [    __DIR__ . '/files/terms.pdf']);remove_action('phpmailer_init', $phpmailerInitAction);wp_mail('test@example.org', 'Second mail without attachments', 'Test 2');

The first wp_mail will be without attachments.The second wp_mail will contain embedded images.The third wp_mail will be without attachments.

It's working fine for now 😎