在php中发送嵌入二进制图像的电子邮件

时间:2015-02-13 16:51:43

标签: php image symfony binary swiftmailer

我试图发送带有图片的电子邮件,但我的服务器中只有二进制代码。 知道怎么做吗?

现在我发送这样的html(以base 64编码):

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

我使用Symfony2的SwiftMailer库发送电子邮件。

完整的示例代码(包含二进制代码的剪切):

//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 = "clientmail@domain.com";
$from_address = "mail@domain.com";
$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);

1 个答案:

答案 0 :(得分:1)

我使用以下代码在电子邮件中嵌入了图片:

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

[full path to you image]替换为图片的路径,例如dirname(__FILE__).'/../images/image.png'