使用python执行shell邮件命令

时间:2015-01-10 07:59:33

标签: python email process subprocess popen3

我使用以下代码按照类似主题的帖子中的建议发送电子邮件。但邮件尚未发送。有什么建议吗?

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")

1 个答案:

答案 0 :(得分:12)

可能无法调用您的函数,请尝试以下代码:

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")

可能有效。祝你好运。