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

Shell转Python发送邮件报错求助:未找到收件人地址

Hey there! Let's get that sendmail error sorted out. The main issues are missing line breaks in your email headers and a small variable typo—here's how to fix it:

What's Going Wrong?

Email standards require each header (From:, To:, Subject:, etc.) to be on its own line, plus a blank line separating headers from the body (even if the body is empty). Your current Python code is cramming all headers into one continuous line, so sendmail can't parse the recipient address correctly. On top of that, there's a typo in your variable name (sender__id instead of sender_id) that would cause a NameError.

Corrected Python Code

import getpass
import subprocess

# Get sender ID (matches your Shell script's `whoami`)
sender_id = getpass.getuser()

# Replace this with your actual recipient list if needed (like "2nd_user" from your Shell script)
userid = getpass.getuser()  # Or set to "2nd_user" directly

# Properly formatted email headers with line breaks
content = f"""Content-Type: text/html; charset=iso-8859-1
Content-Transfer-Encoding: 7bit
From: {sender_id}
To: {userid}
Subject: mail

"""  # Blank line here separates headers from body (required!)

email_path = "/tmp/mail"

# Write to a fresh file (overwrite instead of appending)
with open(email_path, 'w') as f:
    f.write(content)

SENDMAIL = "/usr/lib/sendmail"

# Safer subprocess call without shell=True (avoids security risks)
subprocess.call([SENDMAIL, "-oi", "-t"], stdin=open(email_path, 'r'))

Key Changes Explained:

  • Fixed variable typo: Changed sender__id (double underscore) to sender_id to match your defined variable.
  • Proper header line breaks: Added newlines between each header so sendmail can recognize each field (like the To: recipient).
  • Mandatory blank line: The empty line at the end of the content string tells sendmail where headers end and the body starts.
  • Fresh file write: Switched from 'a' (append) to 'w' (write) to avoid appending to old email files, which could cause messy formatting.
  • Safer subprocess usage: Removed shell=True and passed the command as a list of arguments. This is the recommended approach in Python to avoid shell injection risks.

Quick Note for Recipients

If you meant to send to a specific user (like 2nd_user in your Shell script) instead of yourself, replace userid = getpass.getuser() with userid = "2nd_user" (use a comma-separated list like "user1, user2" for multiple recipients).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:47:53