获取base64 img src并通过电子邮件发送

时间:2015-02-04 19:45:29

标签: php email base64

我正在创建JPEG图片并尝试通过电子邮件发送。但问题是我试图发送的文件出现错误

  

无法访问文件

此功能位于postergenerator.php

function returnImage() {
        ob_start();
        header( "Content-type: image/jpeg" );
        imagejpeg( $my_img,null,100);
        imagecolordeallocate( $line_color );
        imagecolordeallocate( $text_color );
        imagecolordeallocate( $background );
        imagedestroy( $my_img );
        $i = ob_get_clean();
        echo base64_encode( $i ); 
        return base64_encode( $i );
    }

此脚本用于获取映像base64并将其发送到邮件SendEmail.php

$formdata = array();
foreach($_POST as $key => $value )
{
$formdata[$key] = $value;
}
$formdata["resize"] = 1;

include "postergenerator.php";
//returnImage();

require 'PHPMailerAutoload.php';
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "***@gmail.com";
$mail->Password = "****";
$mail->SetFrom("***@gmail.com");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("***@msn.com");

$file_to_attach = returnImage();

$mail->AddAttachment($file_to_attach);

if(!$mail ->Send())
{
    echo 'mailer error:' . $mail->Errorinfo;

}
else
{

echo "Mail has been sent";
}

当我运行SendEmail.php脚本时,输出为:

 <img  src='data:image/jpeg;base64,/9j ****I deleted it***** class="img-responsive">
Could not access file: 
Mail has been sent

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

$mail->addAttachment(..)

仅允许您从本地文件系统添加文件附件。 您的

returnImage()

函数返回base64编码的字符串

在你的情况下,我会做类似的事情:

$mail->Body = sprintf("<img src='data:image/jpeg;base64,%s' alt='' />", returnImage());