PHPMailer Inline String Attachment
Posted by Jason | Posted in mysql, php | Posted on 09-09-2009
1
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
);
}


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
);