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 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('[email protected]','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');