Most easy method for embedding images in emails?

Marcus

Well-known member
I took a look into xenforos source code but did not find a function / class for embedding images within emails. I found this: http://www.zenddeveloper.com/inserting-images-in-email-with-zend-framework/ I guess it would be like this
PHP:
$subject = 'Testsubject';

$mailParams = array( // only used within the template
'user' => $user,
'subject' => "Testmail"
);

$mail = XenForo_Mail::create('MYMAILTEMPLATE', $mailParams, 0); 

$mail->setFrom('somebody@example.com', 'Example Forum');
 
$mail->setSubject($subject);
 
$mail->buildHtml();
 
$mail->send();

PHP:
    public function buildHtml()
    {
        // Important, without this line the example don't work!
        // The images will be attached to the email but these will be not
        // showed inline
        $this->setType(Zend_Mime::MULTIPART_RELATED);
 
        $matches = array();
        preg_match_all("#<img.*?src=['\"]file://([^'\"]+)#i",
        $this->getBodyHtml(true),
        $matches);
        $matches = array_unique($matches[1]);
 
        if (count($matches ) > 0) {
            foreach ($matches as $key => $filename) {
                if (is_readable($filename)) {
                    $at = $this->createAttachment(file_get_contents($filename));
                    $at->type = $this->mimeByExtension($filename);
                    $at->disposition = Zend_Mime::DISPOSITION_INLINE;
                    $at->encoding = Zend_Mime::ENCODING_BASE64;
                    $at->id = 'cid_' . md5_file($filename);
                    $this->setBodyHtml(str_replace('file://' . $filename,
                                      'cid:' . $at->id,
                    $this->getBodyHtml(true)),
                                      'UTF-8',
                    Zend_Mime::ENCODING_8BIT);
                }
            }
        }
    }

PHP:
    public function mimeByExtension($filename)
    {
        if (is_readable($filename) ) {
            $extension = pathinfo($filename, PATHINFO_EXTENSION);
            switch ($extension) {
                case 'gif':
                    $type = 'image/gif';
                    break;
                case 'jpg':
                case 'jpeg':
                    $type = 'image/jpg';
                    break;
                case 'png':
                    $type = 'image/png';
                    break;
                default:
                    $type = 'application/octet-stream';
            }
        }
 
        return $type;
    }
 
Top Bottom