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

Python邮件发送器测试报错:无法找到同目录下的download.jpg文件

Fixing the "No such file or directory" Error for Your Python Email Sender

Hey there! Let's break down why your script can't locate download.jpg even though it's in the same folder as your code, and fix it for good.

Why This Happens

The most common culprit here is your script's current working directory doesn't match the folder where your script and image are stored. For example:

  • If you run the script from a different folder in the terminal (like python ../projects/email_script.py), Python will look for download.jpg in your terminal's current folder, not the script's folder.
  • Some IDEs default to a different working directory (like your user home folder) instead of the script's directory.

Step-by-Step Fixes

1. First, Verify the Problem

Add a quick debug line to check where Python is looking for the file. Insert this at the top of your script (after imports):

import os
print("Current working directory:", os.getcwd())

Run the script and compare the printed path to the folder where your script and download.jpg live. If they don't match, that's exactly the issue.

2. Use Absolute File Paths (Most Reliable Fix)

Instead of using a relative filename like download.jpg, build the absolute path using your script's location. This way, no matter where you run the script from, it'll always find the image.

Modify your code where you define filename like this:

# Add os import at the top if you don't have it already
import os

def EmailSender():
    # ... keep your existing code above ...
    
    # Get the folder where your script is located
    script_directory = os.path.dirname(os.path.abspath(__file__))
    # Combine the script folder path with the image filename
    filename = os.path.join(script_directory, 'download.jpg')
    
    # ... rest of your code for attaching the file ...

3. Quick Temporary Fix (For Testing)

If you just want to test quickly without modifying code:

  • Terminal: Navigate to the folder containing your script and image first (cd /path/to/your/folder), then run python your_script.py.
  • IDE: Go to your IDE's run settings and set the "Working Directory" to the folder where your script and image are stored.

Bonus: Fix the Unsent Email

I noticed your code logs into the SMTP server but never actually sends the email! Add this line right after srv.login(...) and before srv.quit():

srv.sendmail(email_user, email_send, text)

Otherwise, your script will connect, login, then disconnect without sending anything.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 14:17:43