使用Python执行Shell邮件命令

7
我已经使用以下代码来发送电子邮件,这是在类似主题的帖子中建议的。但是邮件没有发送成功。有什么建议吗?
import subprocess
recipient = 'xxxxx@gmail.com'
subject = 'test'
body = 'testing mail through python'
def send_message(recipient, subject, body):
    process = subprocess.Popen(['mail', '-s', subject, recipient],
                               stdin=subprocess.PIPE)
    process.communicate(body)

print("sent the email")

2
你调用了send_message()函数吗? - lqhcpsgbl
在你的机器上,命令行中是否可以使用 mail -s ... 命令?如果不能,那么 subprocess 也无法使其工作。你可以使用 smtplib 发送电子邮件 - jfs
1个回答

14

你的函数可能不会被调用,请尝试以下代码:

import subprocess

recipient = 'xxxxx@gmail.com'
subject = 'test'
body = 'testing mail through python'

def send_message(recipient, subject, body):
    try:
      process = subprocess.Popen(['mail', '-s', subject, recipient],
                               stdin=subprocess.PIPE)
    except Exception, error:
      print error
    process.communicate(body)

send_message(recipient, subject, body)

print("sent the email")

五月份工作顺利。祝好运。


如果在Windows中运行,会看到以下错误:Traceback (most recent call last): File "C:/Python34/Scripts/sending_gmail_3.py", line 12, in send_message(recipient, subject, body) File "C:/Python34/Scripts/sending_gmail_3.py", line 10, in send_message stdin=subprocess.PIPE) File "C:\Python34\lib\subprocess.py", line 858, in __init__ restore_signals, start_new_session) File "C:\Python34\lib\subprocess.py", line 1111, in _execute_child startupinfo) FileNotFoundError: [WinError 2] 系统找不到指定的文件 - sandy
3
当然可以。在Windows中不存在mail命令。 - Jonas Gröger
1
在Python 3.x中,将body = b'testing mail through python'更改为使其工作。 - kateryna
@iqhcpsgbl = 在上面的例子中,我们如何添加附件?我需要附加CSV文件... - viki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接