通过Pythons子进程使用newline和Linux mail命令发送邮件

2024-10-05 14:31:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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/日志/邮件.err显示以下内容

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

我发现一个建议是

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

然而,这并没有解决问题。你知道吗

有什么建议吗?你知道吗


Tags: testimportcmdcomyourisexampleusername
2条回答

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

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

在python3.7之前,您需要将text=True替换为更旧、更不清楚的别名universal_newlines=Trueinput参数可能是在python3.3中引入的。有关如何在旧版本中执行类似操作的idas以及更详细的讨论,请参见Running Bash commands in Python

你需要在正文和主题中加引号。如果你用f字串就容易多了

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

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

相关问题 更多 >