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

Cronjob执行PHPMailer发送邮件时内嵌图片无法显示问题

Fixing Embedded Image Issue with PHPMailer in Cron Jobs

The root cause here is almost always working directory mismatch between running the script via browser vs. cron. Let's break this down and fix it:

Why this happens

When you run the script in a browser, PHP's working directory is the folder where your test2.php lives (/var/www/html/work/). So the relative path dedicated.png points to the correct file.

But cron jobs run with the executing user's default working directory (for root, that's usually /root/). When cron runs your script, it looks for dedicated.png in /root/ instead of /var/www/html/work/—hence the missing image.

Solutions to try

1. Use an absolute path for the image

Update your AddEmbeddedImage call to use the full absolute path of the image file. This is the most reliable method:

$mail->AddEmbeddedImage("/var/www/html/work/dedicated.png", "logoimg", "dedicated.png");

No matter where the script runs, it'll always point to the correct file location.

2. Change working directory in the cron command

Modify your cron job to first navigate to the script's directory before executing it. This makes cron use the same working directory as when you run it in the browser:

* * * * * root cd /var/www/html/work && php test.php

The && ensures the php command only runs if the cd succeeds.

3. Set the working directory in your PHP script

Add this line at the very top of your test2.php file to force PHP to switch to the script's directory when it runs:

// For PHP 5.3 and above
chdir(__DIR__);

// For older PHP versions
// chdir(dirname(__FILE__));

This way, any relative paths in your script will resolve correctly, regardless of where it's executed from.

Quick debugging tip

To confirm the working directory issue, add this line to your script and check the output file after cron runs:

file_put_contents('/tmp/cron_working_dir.txt', getcwd() . PHP_EOL);

Open /tmp/cron_working_dir.txt—it'll show you exactly where cron is looking for files, which should confirm the path mismatch.

内容的提问来源于stack exchange,提问作者user9053749

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:42:06