You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现调用WordPress文件夹随机图片作为Outlook邮件签名

随机图片嵌入Outlook邮件实现方案

原有代码失效原因

  • PHP属于服务端执行的脚本,无法在邮件HTML中运行,所有邮件客户端都不会解析邮件内的PHP代码
  • 代码中的路径/images/random/image _与你实际存放图片的路径不匹配,且存在多余空格
  • 随机数范围仅设置了1-2,无法覆盖你存放的5张图片

方案1:服务端随机图片接口(推荐,全邮件客户端兼容)

该方案不需要在邮件内嵌入任何脚本,完全兼容Outlook所有版本:

  1. 在你的图片存放目录https://domain.tld/_wordpress/wp-content/uploads/images/下新建random.php文件,写入以下代码:
<?php
// 配置图片总数
$total_images = 5;
// 生成1-5的随机数
$random_id = rand(1, $total_images);
// 拼接本地图片路径
$image_file = __DIR__ . "/{$random_id}.png";

// 验证图片存在
if (!file_exists($image_file)) {
    // 图片不存在时返回默认图,可自行修改
    $image_file = __DIR__ . "/1.png";
}

// 输出图片响应头
header("Content-Type: image/png");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
// 输出图片内容
readfile($image_file);
exit;
?>
  1. 邮件中直接用该接口地址作为图片src即可:
<img src="https://domain.tld/_wordpress/wp-content/uploads/images/random.php" alt="志愿工作宣传图" height="201" width="600" />

每次加载邮件时,服务端会自动返回随机图片,完全符合Outlook的安全规则。

方案2:前端JS实现(仅支持网页版Outlook)

注意:Outlook桌面版默认禁用所有JavaScript,该方案不推荐用于正式宣传场景
直接在邮件HTML中插入以下代码即可:

<div id="volunteer-img-wrapper"></div>
<script>
// 图片总数
const totalImg = 5;
// 生成1-5随机数
const randomId = Math.floor(Math.random() * totalImg) + 1;
// 拼接图片地址
const imgUrl = `https://domain.tld/_wordpress/wp-content/uploads/images/${randomId}.png`;
// 插入图片
document.getElementById('volunteer-img-wrapper').innerHTML = `<img src="${imgUrl}" alt="志愿工作宣传图" height="201" width="600" />`;
</script>

注意事项

  • 确保图片目录没有设置防盗链,且所有图片对外开放访问权限
  • 推荐优先使用方案1,避免不同版本Outlook的兼容性问题

内容的提问来源于stack exchange,提问作者Thomas D.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 15:24:05