简体   繁体   中英

How add inline images in mailgun using PHP and image contents instead of path

I am trying to add an inline image to an email sent using the mailgun api using only the contents of the image file.

As far as i know mailgun-php only allows for paths to be specified in the inline element.

Is there a way to add images using their contents without modifying the mailgun-php library?

I've tried inlining the whole thing inside of html img tag but that doesn't work in all email clients (for instance gmail):

<img src="data:image/png;base64,BASE64CONTENTSHERE==" />

I have not found a way to do this without modifying the mailgun-php code so I eneded up using the following to store the file in the temporary folder.

        $prefix = 'someprefix'; // Used to easily identify the file if needed
        $filename = uniqid($prefix, true).'.png';
        $path = sys_get_temp_dir().DIRECTORY_SEPARATOR.$filename;
        $f = fopen($path, 'w');
        fwrite($f, $binaryImageContent);   
        fclose($f); 

Then to send the email and remove the temporary file

        $mailgun = new \MailgunClient();
        $response = $mailgun->sendEmail(
            $fromEmail,
            $replyTo,
            array($toEmail), 
            $subject,
            $html,
            array(
              'inline' => $path
            )                    
        );

        unlink($path);

Below is what the MailgunClient class looks like, I had to explicitly set the Guzzle http client, since the default was failing. Note MAILGUN_API_KEY and MAILGUN_DOMAIN have to be set as constants somewhere else in the code using define('MAILGUN_API_KEY', 'key_here'); and define('MAILGUN_DOMAIN', 'domain.com');

<?php

use Mailgun\Mailgun;

class MailgunClient {

    public function sendEmail($from, $replyTo, $to, $subject, $html, $inline = null) {
        $client = new \Http\Adapter\Guzzle6\Client();
        $mailgun = new \Mailgun\Mailgun(MAILGUN_API_KEY, $client);        
        $domain = MAILGUN_DOMAIN;

        $params = array();
        $params['from'] = $from;
        $params['h:Reply-To'] = $replyTo;
        $params['subject'] = $subject;
        $params['text'] = $html;
        $params['html'] = $html;
        $params['inline'] = $inline;
        $params['to'] = $to;

        $mailgun->sendMessage($domain, $params, $inline);     
    }

}

Finally in the email use the following tag to reference the inlined image. The src attribute has to be cid:the_filename_created to match what the library outputs in the email.

 <img src="cid:'.$filename.'.png" alt="logo" style="width:auto;height:150px;max-height:150px;"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM