在 python 脚本中通过邮件命令发送电子邮件

Send email via mail command in python script

我正在尝试发送多行文本:

text = "This is a line 1
This is a line 2
This is a line 3"

在 python 脚本中:

cmd = "echo {} | mail -s 'Test email' name@server.com".format(text)
os.system(cmd) 

但是我得到一个错误,因为新行被解释为命令:

sh: line 1: This: command not found

打印出来,结果是:

echo This is line 1
This is line 2
This is line 3 | mail -s 'Test email' name@server.com

我觉得解决方法很简单,但是我没有找到任何有用的解决方法。

直接的问题是 shell 中的字符串如果包含换行符等则需要用引号引起来。参见 When to wrap quotes around a shell variable

但更根本的是,您真的不想像这样在这里使用 os.system。就像它的文档已经告诉你的那样,你通常更喜欢 subprocess.

import subprocess

subprocess.run(
    ["mail", "-s", "Test email", "name@server.com"], 
    input=text, text=True, check=True)

或使用 smtplib 本地发送电子邮件(或者相反,如果您只需要一个简单的 shell 脚本,则根本不要使用 Python,尽管您会然后仍然需要修复引号)。

mail 的可移植性很差,所以如果您还没有在您的系统上测试过它,它可能会有其他问题。 或许还可以参见 How do I send a file as an email attachment using Linux command line?