jpintor
jpintor

Reputation: 419

Send email with embedding binary image in php

I'm trying to send email with images, but only have the binary code in my server. Any idea how to do it?

Now I'm sending the html like this (in base 64 encoded):

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

I'm using the SwiftMailer library from Symfony2 to send the emails.

A full example code (with cuts in the binary code):

//params
$subject = "Demo e-mail";
$body = "<html>
    <table>
        <tr>
            <td>
                <img src='data:image/png; base64, iVBORw0KGgo...zIIAAAAASUVORK5CYII='>
            </td>
            <td style='padding-left:20px'>
                <div>
                    <h3>Product name</h3>
                    <h4>Code 3089</h4>
                    <p>14.70 $</p>
                </div>
              </td>
        </tr>
    </table>
    </html>";
$name = "Client name";
$email = "[email protected]";
$from_address = "[email protected]";
$from_name = "App Name";

//SwiftMessag eobject 
$message = \Swift_Message::newInstance()
        ->setSubject($subject)
        ->setFrom(array($from_address => $from_name))
        ->setTo(array($email => $name))
        ->setBody($body, 'text/html');

//send email
$this->get('mailer')->send($message);

Upvotes: 1

Views: 1262

Answers (1)

A.L
A.L

Reputation: 10503

I embedded an image in an email with this code:

$message = \Swift_Message::newInstance();

$body = '<html><head></head><body>'.
    '<p><img src="'.$message->embed(\Swift_Image::fromPath(
        \Swift_Attachment::fromPath([full path to you image]
    )
    ->setDisposition('inline'))).'" alt="Image" /></p>'.
    '</body></html>'
;

$message
    ->setSubject('Subject')
    ->setFrom($from)
    ->setTo($to)
    ->setBody(
        $body,
        'text/html'
    )
;

$this->mailer->send($message);

Replace [full path to you image] with a path to your image, for example dirname(__FILE__).'/../images/image.png'.

Upvotes: 1

Related Questions