【问题标题】:Get images from the array and embed them in the email body从数组中获取图像并将它们嵌入到电子邮件正文中
【发布时间】:2014-05-24 14:34:33
【问题描述】:

我正在使用 wordpress cms 和 PHPMailer。在我的表单处理器中,我有一个简单的循环,它生成一组选定的图像。请检查下面的相关代码块。它基本上根据通过表单提供的帖子 ID 生成图像数组。我需要提取所有这些图像并将它们嵌入电子邮件正文中。请注意,我不打算将这些图像作为附件发送。这是一个剥离的代码版本。

$email = new PHPMailer();
$email->From      = 'John@example.com';
$email->FromName  = 'John Doe';
$email->Subject   = 'This is the subject of the message';                        
$body = '<table><tr><td>';

$body .=  
    $args = array('post__in' => $short_ids, 'post_type' => 'post');
    $posts = get_posts($args);

    foreach ($posts as $post) : ?>
    <?php $images = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'cover' );

    $img_url = $images[0];
    $email->AddEmbeddedImage($img_url, '1243');?>
    <img src="cid:1243"/>               
    <?php endforeach;?>

$body = '</td></tr></table><tr>';
$email->MsgHTML($body);
$email->IsHTML(true); 
$email->AddAddress( 'email@gmail.com' );
$email->Send();

我刚刚在电子邮件正文中看到了 Array 这个词。如何将此数组 > 转换为要嵌入电子邮件正文的图像?所以我想我基本上需要数组操作方面的帮助。


更新:这是我想出的另一个代码,它成功地从数组中获取图像并实际回显到页面上,但 不嵌入图像电子邮件正文。

foreach ($posts as $post) : ?>
  <?php $images = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'cover' );
  $img_urls = $images[0]; ?>
  <img src="<?php echo $img_urls;?>">
<?php endforeach;

【问题讨论】:

    标签: arrays email phpmailer


    【解决方案1】:

    事实证明,您不一定需要 AddEmbeddedImage 来使用 PHPMailer 在正文中嵌入图像。您可以通过将代码结果附加到 $body 变量来以原生 php 方式执行此操作,然后使用 PHPMailer 的 $email-&gt;MsgHTML($body) 获取输出。下面是相关代码,根据存储在$select_ids 中的post-ids 提取多个post-thumbnails 并将结果附加到$body 变量。

    $args = array('post__in' => $select_ids, 'post_type' => 'post');
    
    $posts = get_posts($args);
    foreach ($posts as $post) {
    $images = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'cover');
    $body .=    '<a href="'.get_permalink().'"><img src="'.$images[0].'"></a>';             
    } 
    

    如果您是新手,我想指出我在脚本中犯的一个愚蠢错误。如果您在第一行和第二行中设置一个数组,请确保不要将$body$body. = 变量放在它前面,否则您的代码将在您的html 输出中输出不需要的单词Array,这又是我在 html 输出中得到 Array 这个词的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 2022-09-25
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      • 2016-09-07
      • 1970-01-01
      相关资源
      最近更新 更多