2015-01-10 140 views
2

我已經使用下面的代碼來發送電子郵件,如同類似主題的帖子之一中建議的。但郵件尚未發送。有什麼建議麼?使用python執行shell郵件命令

import subprocess 
recipient = '[email protected]' 
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()? –

+0

'mail -s ...'是否在你的機器上的命令行上工作?如果不; 'subprocess'不會使它工作。您可以[使用'smtplib'發送電子郵件](http://stackoverflow.com/a/20787826/4279) – jfs

回答

5

你的功能可能無法被調用,試試這個代碼:

import subprocess 

recipient = '[email protected]' 
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") 

五月的作品。祝你好運。

+0

如果在窗口中運行相同的代碼,它會不工作嗎? – sandy

+0

如果在窗口中運行,看到下面的錯誤 'Traceback(最近調用最後一個): 文件「C:/Python34/Scripts/sending_gmail_3.py」,第12行,在 send_message(收件人,主題,正文) 文件「C:/ Python34/Scripts/sending_gmail_3。 py「,第10行,在send_message stdin = subprocess.PIPE) 文件」C:\ Python34 \ lib \ subprocess.py「,行858,在__init__中 restore_signals,start_new_session) 文件」C:\ Python34 \ lib \ subprocess.py「,行1111,在_execute_child startupinfo) FileNotFoundError:[WinError 2]系統找不到指定的文件' – sandy

+1

@sandy當然。 Windows中不存在'mail'命令。 –