使用python执行shell邮件命令

san*_*ndy 6 python email subprocess process 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")
Run Code Online (Sandbox Code Playgroud)

lqh*_*gbl 13

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

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")
Run Code Online (Sandbox Code Playgroud)

可能有效.祝好运.

  • @sandy 当然。Windows 中不存在 `mail` 命令。 (2认同)