通过 Pythons 子进程使用换行符和 Linux 邮件命令发送邮件



我想使用用户名和随机生成的密码生成帐户。然而。我无法发送多行邮件。显示我问题的最小代码是:

import subprocess
import string
username = Test
randomPassword = abcabc
fromAddr='test@example.com'
toAddr='receive@example.com'
subject='Test Mail'
body='Your Username is ' + username + 'n'+'Your Password is' + randomPassword
cmd='echo '+body+' | mail -s '+subject+' -r '+fromAddr+' '+toAddr
send=subprocess.call(cmd,shell=True)

错误是:

mail: cannot send message: process exited with a non-zero status
/

var/log/mail.err 显示以下内容

[SERVERNAME] sSMTP[9002]: RCPT TO:<[SUBJECT]@[SERVERNAME]> (Domain does not exist: [SERVERNME])

我发现的一个建议是使用

cmd='echo -e ' +body+ [...] 

然而,这并没有解决问题。

有什么建议吗?

您需要

将正文和主题放在引号中。如果使用 f 字符串会更容易

cmd  = f"echo '{body}' | mail -s '{subject}' -r '{fromAddr}' '{toAddr}'"

请注意,您需要确保任何参数中都没有引号字符 - 确保密码中不允许使用单引号。

你真的想避免巴马尔答案的各种引用问题。如果你的Python足够新,你想要

send = subprocess.call(
    ['mail', '-s', subject, '-r', fromAddr, toAddr],
    input=body, text=True)

在 Python 3.7 之前,您需要将 text=True 替换为较旧的、更不清楚的别名universal_newlines=Trueinput论点可能是在Python 3.3中引入的。有关如何在旧版本中执行类似操作的 idas 以及更详细的讨论,请参阅 在 Python 中运行 Bash 命令

最新更新