php 如何在html电子邮件中嵌入图像

lnlaulya  于 2022-12-25  发布在  PHP
关注(0)|答案(8)|浏览(206)

我正试图实现一个代码来发送嵌入图像的HTML电子邮件。
我已经尝试了简单的HTML电子邮件与图像,但这张图片是从服务器。

jmp7cifd

jmp7cifd1#

我强烈建议使用PHPMailer这样的库来发送电子邮件。
它更容易,并自动为您处理大多数问题。
关于显示嵌入(内联)图像,以下是他们的文档:
内联附件
还有一种添加附件的方法。如果您想制作一个HTML电子邮件,其中包含桌面中包含的图像,则必须附加图像,然后将标记链接到该图像。例如,如果您将图像添加为CID my-photo的内联附件,则可以使用<img src="cid:my-photo" alt="my-photo" />在HTML电子邮件中访问该图像。
具体来说,这里是添加内联附件的函数:

$mail->AddEmbeddedImage(filename, cid, name);
//By using this function with this example's value above, results in this code:
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg ');

为了给你一个更完整的例子来说明它是如何工作的:

<?php
require_once('../class.phpmailer.php');
$mail = new PHPMailer(true); // the true param means it will throw exceptions on     errors, which we need to catch

$mail->IsSMTP(); // telling the class to use SMTP

try {
  $mail->Host       = "mail.yourdomain.com"; // SMTP server
  $mail->Port       = 25;                    // set the SMTP port
  $mail->SetFrom('name@yourdomain.com', 'First Last');
  $mail->AddAddress('whoto@otherdomain.com', 'John Doe');
  $mail->Subject = 'PHPMailer Test';

  $mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
  $mail->Body = 'Your <b>HTML</b> with an embedded Image: <img src="cid:my-attach"> Here is an image!';

  $mail->AddAttachment('something.zip'); // this is a regular attachment (Not inline)
  $mail->Send();
  echo "Message Sent OK<p></p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}
?>

编辑:

关于你的评论,你问如何发送HTML电子邮件与嵌入式图像,所以我给你一个例子,如何做到这一点。
我之前提到的库可以使用SMTP以外的许多方法发送电子邮件。
查看PHPMailer Example page以获取其他示例。
无论如何,如果您不想以库支持的方式发送电子邮件,您仍然可以(应该)使用库来构建消息,然后以您想要的方式发送。
例如:
您可以替换发送电子邮件的行:

$mail->Send();

用这个:

$mime_message = $mail->CreateBody(); //Retrieve the message content
echo $mime_message; // Echo it to the screen or send it using whatever method you want
9jyewag0

9jyewag02#

我正在使用这个功能,找到我的信中的所有图像,并将其附加到邮件中。

**参数:**获取您的HTML(您要发送的);
**返回:**必要的HTML和头,可以在mail()中使用;
示例用法:

define("DEFCALLBACKMAIL", "yourmail@yourdomain.com"); // WIll be shown as "from".
$final_msg = preparehtmlmail($html); // give a function your html*

mail('your@mail.com', 'your subject', $final_msg['multipart'], $final_msg['headers']); 
// send email with all images from html attached to letter

function preparehtmlmail($html) {

  preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
  $i = 0;
  $paths = array();

  foreach ($matches[1] as $img) {
    $img_old = $img;

    if(strpos($img, "http://") == false) {
      $uri = parse_url($img);
      $paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
      $content_id = md5($img);
      $html = str_replace($img_old,'cid:'.$content_id,$html);
      $paths[$i++]['cid'] = $content_id;
    }
  }

  $boundary = "--".md5(uniqid(time()));
  $headers .= "MIME-Version: 1.0\n";
  $headers .="Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
  $headers .= "From: ".DEFCALLBACKMAIL."\r\n";
  $multipart = '';
  $multipart .= "--$boundary\n";
  $kod = 'utf-8';
  $multipart .= "Content-Type: text/html; charset=$kod\n";
  $multipart .= "Content-Transfer-Encoding: Quot-Printed\n\n";
  $multipart .= "$html\n\n";

  foreach ($paths as $path) {
    if(file_exists($path['path']))
      $fp = fopen($path['path'],"r");
      if (!$fp)  {
        return false;
      }

    $imagetype = substr(strrchr($path['path'], '.' ),1);
    $file = fread($fp, filesize($path['path']));
    fclose($fp);

    $message_part = "";

    switch ($imagetype) {
      case 'png':
      case 'PNG':
            $message_part .= "Content-Type: image/png";
            break;
      case 'jpg':
      case 'jpeg':
      case 'JPG':
      case 'JPEG':
            $message_part .= "Content-Type: image/jpeg";
            break;
      case 'gif':
      case 'GIF':
            $message_part .= "Content-Type: image/gif";
            break;
    }

    $message_part .= "; file_name = \"$path\"\n";
    $message_part .= 'Content-ID: <'.$path['cid'].">\n";
    $message_part .= "Content-Transfer-Encoding: base64\n";
    $message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
    $message_part .= chunk_split(base64_encode($file))."\n";
    $multipart .= "--$boundary\n".$message_part."\n";

  }

  $multipart .= "--$boundary--\n";
  return array('multipart' => $multipart, 'headers' => $headers);  
}
cwtwac6a

cwtwac6a3#

PHPMailer可以自动嵌入HTML邮件中的图片。在编写HTML时,您必须给予文件系统中的完整路径:

<img src="/var/www/host/images/photo.png" alt="my photo" />

它将自动转换为:

<img src="cid:photo.png" alt="my photo" />
nc1teljy

nc1teljy4#

根据亚瑟·哈尔马的回答,我做了以下正确的工作与苹果的,Android和iOS的邮件。

define("EMAIL_DOMAIN", "yourdomain.com");

public function send_email_html($to, $from, $subject, $html) {
  preg_match_all('~<img.*?src=.([\/.a-z0-9:_-]+).*?>~si',$html,$matches);
  $i = 0;
  $paths = array();
  foreach ($matches[1] as $img) {
    $img_old = $img;
    if(strpos($img, "http://") == false) {
      $uri = parse_url($img);
      $paths[$i]['path'] = $_SERVER['DOCUMENT_ROOT'].$uri['path'];
      $content_id = md5($img);
      $html = str_replace($img_old,'cid:'.$content_id,$html);
      $paths[$i++]['cid'] = $content_id;
    }
  }
  $uniqid   = md5(uniqid(time()));
  $boundary = "--==_mimepart_".$uniqid;

  $headers = "From: ".$from."\n".
  'Reply-to: '.$from."\n".
  'Return-Path: '.$from."\n".
  'Message-ID: <'.$uniqid.'@'.EMAIL_DOMAIN.">\n".
  'Date: '.gmdate('D, d M Y H:i:s', time())."\n".
  'Mime-Version: 1.0'."\n".
  'Content-Type: multipart/related;'."\n".
  '  boundary='.$boundary.";\n".
  '  charset=UTF-8'."\n".
  'X-Mailer: PHP/' . phpversion();

  $multipart = '';
  $multipart .= "--$boundary\n";
  $kod = 'UTF-8';
  $multipart .= "Content-Type: text/html; charset=$kod\n";
  $multipart .= "Content-Transfer-Encoding: 7-bit\n\n";
  $multipart .= "$html\n\n";
  foreach ($paths as $path) {
    if (file_exists($path['path']))
      $fp = fopen($path['path'],"r");
      if (!$fp)  {
        return false;
      }
    $imagetype = substr(strrchr($path['path'], '.' ),1);
    $file = fread($fp, filesize($path['path']));
    fclose($fp);
    $message_part = "";
    switch ($imagetype) {
      case 'png':
      case 'PNG':
            $message_part .= "Content-Type: image/png";
            break;
      case 'jpg':
      case 'jpeg':
      case 'JPG':
      case 'JPEG':
            $message_part .= "Content-Type: image/jpeg";
            break;
      case 'gif':
      case 'GIF':
            $message_part .= "Content-Type: image/gif";
            break;
    }
    $message_part .= "; file_name = \"$path\"\n";
    $message_part .= 'Content-ID: <'.$path['cid'].">\n";
    $message_part .= "Content-Transfer-Encoding: base64\n";
    $message_part .= "Content-Disposition: inline; filename = \"".basename($path['path'])."\"\n\n";
    $message_part .= chunk_split(base64_encode($file))."\n";
    $multipart .= "--$boundary\n".$message_part."\n";
  }
  $multipart .= "--$boundary--\n";
  mail($to, $subject, $multipart, $headers);
}
1cosmwyk

1cosmwyk5#

这是我用来在HTML邮件和PDF文档中嵌入图像的代码。

<?php
$logo_path = 'http://localhost/img/logo.jpg';
$type = pathinfo($logo_path, PATHINFO_EXTENSION);
$image_contents = file_get_contents($logo_path);
$image64 = 'data:image/' . $type . ';base64,' . base64_encode($image_contents);
?>
<img src="<?php echo $image64 ?>" />
whlutmcx

whlutmcx6#

你必须把你的电子邮件编码为多部分的mime,然后你可以把电子邮件作为附件,你在电子邮件中通过cid引用它们。
或者,您可以不附加到电子邮件和直接使用网址,但大多数邮件程序将阻止这一点作为垃圾邮件发送者使用的伎俩,以检测活跃的电子邮件地址。
你没有说是什么语言,但这里有一个example

zu0ti5jz

zu0ti5jz7#

这里有一种方法可以获得一个字符串变量,而不必担心编码。
如果您有 Mozilla Thunderbird,您可以使用它来获取html图像代码。
我在这里写了一个小教程,并附上了一个截图(这是针对powershell的,但这并不重要):
powershell电子邮件与html图片显示红色x
再一次:
如何在电子邮件中嵌入图像

4nkexdtk

4nkexdtk8#

我用golang命令行来做这个工作,关键部分是做cid替换:
https://github.com/gonejack/embed-email

相关问题