【问题标题】:Send email with embedding binary image in php在 php 中发送带有嵌入二进制图像的电子邮件
【发布时间】:2015-04-14 19:00:36
【问题描述】:

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

现在我发送这样的 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);

【问题讨论】:

  • 我刚刚看到data: 是重复的。你可以只用一个data:吗?
  • 好的,复制/粘贴问题,但在项目中没有重复。这不是问题。
  • 如何将此图像发送到 Swiftmailer?请出示完整代码。

标签: php image symfony binary swiftmailer


【解决方案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'

【讨论】:

  • 是的,这是发送带有绝对路径的图像的方式。但是,我的问题是我是否可以发送图像二进制文件,因为图像文件不在我的服务器中,而这些服务器只返回二进制代码。有什么办法吗?
  • @jpintor 很抱歉,它对您没有帮助。您可以尝试将服务器上的二进制代码保存为 PNG 文件,然后嵌入此图像吗?
  • 是的,我可以将图像保存在文件中,但我想避免它。但是,我会尝试这样做并稍后删除该文件。
猜你喜欢
  • 2012-04-07
  • 2021-10-31
  • 1970-01-01
  • 2015-07-29
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 2012-12-08
相关资源
最近更新 更多