Display inline image attachments with wp_mail

attachment, base64, email, wordpress

Solution

`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 attachment

global $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.

Problem

I have a problem. I would like to attach an image to an email and also display it inline, with some other php-generated content. The problem is I don't have the slightest ideea how to use inline a file attachment array used by wp_mail to attach. My solution was to encode the images in base64 and put them inline the HTML like this: ``` <img alt="The Alt" src="data:image/png;base64,*etc*etc*etc" /> ``` But the problem is that Gmail / Outlook remove the src data from the image. So it lands as ``` <img alt="The Alt" /> ``` Any clues what to modify (headers to work with base64) or how to use attachment to embed them inline?

Original source