社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

ChrizZ • 5 年前 • 1502 次点击  

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

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+ [...] 

但这并没有解决问题。

有什么建议吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/45905
 
1502 次点击  
文章 [ 2 ]  |  最新文章 5 年前
tripleee
Reply   •   1 楼
tripleee    5 年前

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

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

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

Barmar
Reply   •   2 楼
Barmar    5 年前

你需要把身体和主题用引号引起来。如果你用F字串就容易多了

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

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