PHPMailer Inline String Attachment

by Jason on September 9, 2009

Recently, while using PHPMailer, I needed the ability to have an inline string attachment, however this functionality is not present as of version 5.0.2, so I wrote my own.

For those who don’t know, PHPMailer has a number of ways you can create email attachments:

  • Standard Attachment – works as you’d expect
  • Inline Attachment – attachments you can reference in the message body. For instance, if you attach an image, you can then reference that image using the IMG tag in the body
  • String Attachment – builds an attachment from blob data (usually stored in a database)

Inline attachments and String attachments rock, however there was no combination of the two. So, I wrote one. Simply add this block of code to your phpmailer class and you’re good to go.


  /**
   * Adds a string or binary attachment (non-filesystem) to the list.
   * This method can be used to attach ascii or binary data,
   * such as a BLOB record from a database.
   * @param string $string String attachment data.
   * @param string $cid Content ID of the attachment.  Use this to identify
   *        the Id for accessing the image in an HTML form.
   * @param string $filename Name of the attachment.
   * @param string $encoding File encoding (see $Encoding).
   * @param string $type File extension (MIME) type.
   * @return void
   */
  public function AddInlineStringAttachment($string, $cid, $filename, $encoding = 'base64', $type = 'application/octet-stream') {
    // Append to $attachment array
    $this->attachment[] = array(
      0 => $string,
      1 => $filename,
      2 => $filename,
      3 => $encoding,
      4 => $type,
      5 => true,  // isStringAttachment
      6 => 'inline',
      7 => $cid
    );
  }

2 comments

Hi,

In the original the attached filename contained the path (prepended) with slashed replaced by underscores so I modded the code to;

$onlyfilename = basename($filename);
$this->attachment[] = array(
0 => $string,
1 => $filename,
2 => $onlyfilename,
3 => $encoding,
4 => $type,
5 => true, // isStringAttachment
6 => ‘inline’,
7 => $cid
);

by Tony on September 17, 2009 at 5:38 pm. #

thank you it is very usefull
note:
in fix there is wrong apostrophe around ‘inline’, php did not alert me and it was not working
using
6 => ‘inline’,
is working perfectly

by Tomas on April 18, 2011 at 8:03 am. #

Leave your comment

Required.

Required. Not published.

If you have one.