2008-09-15 80 views
93

我使用以下方法使用SMTP從Python發送郵件。這是使用正確的方法還是有我缺少的陷阱?使用SMTP從Python發送郵件

from smtplib import SMTP 
import datetime 

debuglevel = 0 

smtp = SMTP() 
smtp.set_debuglevel(debuglevel) 
smtp.connect('YOUR.MAIL.SERVER', 26) 
smtp.login('[email protected]', 'PASSWORD') 

from_addr = "John Doe <[email protected]>" 
to_addr = "[email protected]" 

subj = "hello" 
date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M") 

message_text = "Hello\nThis is a mail from your server\n\nBye\n" 

msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" 
     % (from_addr, to_addr, subj, date, message_text) 

smtp.sendmail(from_addr, to_addr, msg) 
smtp.quit() 
+2

確保您獲得日期/時間正確。我發現以下功能非常有用,它爲Date-Header提供了完美格式化的值: http://docs.python.org/py3k/library/email.util.html#email.utils.formatdate – BastiBen 2010-07-30 06:11:21

+0

這裏是一個代碼示例,允許[在主題和/或正文中發送帶有Unicode文本的電子郵件](http://stackoverflow.com/a/20787826/4279) – jfs 2013-12-26 18:10:11

+0

這裏是一個代碼示例,演示如何[發送圖像內聯電子郵件與HTML和純文本部分)](http://stackoverflow.com/a/20485764/4279)。它還展示瞭如何在舊的Python版本上配置ssl參數。 – jfs 2013-12-26 18:11:00

回答

94

我使用的腳本非常相似;我在這裏發佈它作爲如何使用電子郵件。*模塊生成MIME消息的示例;所以這個腳本可以很容易地修改爲附加圖片等。

我依靠我的ISP添加日期時間標題。

我的ISP要求我使用安全SMTP發送郵件,我靠ssmtplib模塊(在http://www1.cs.columbia.edu/~db2501/ssmtplib.py下載)

在你的腳本,用戶名和密碼,(下面給出虛值),用於在SMTP服務器上進行身份驗證,在源文件中以純文本格式。這是一個安全弱點;但最好的選擇取決於你需要多麼謹慎(想要?)來保護這些。

=======================================

#! /usr/local/bin/python 


SMTPserver = 'smtp.att.yahoo.com' 
sender =  '[email protected]_email_domain.net' 
destination = ['[email protected]_email_domain.com'] 

USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER" 
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER" 

# typical values for text_subtype are plain, html, xml 
text_subtype = 'plain' 


content="""\ 
Test message 
""" 

subject="Sent from Python" 

import sys 
import os 
import re 

from smtplib import SMTP_SSL as SMTP  # this invokes the secure SMTP protocol (port 465, uses SSL) 
# from smtplib import SMTP     # use this for standard SMTP protocol (port 25, no encryption) 

# old version 
# from email.MIMEText import MIMEText 
from email.mime.text import MIMEText 

try: 
    msg = MIMEText(content, text_subtype) 
    msg['Subject']=  subject 
    msg['From'] = sender # some SMTP servers will do this automatically, not all 

    conn = SMTP(SMTPserver) 
    conn.set_debuglevel(False) 
    conn.login(USERNAME, PASSWORD) 
    try: 
     conn.sendmail(sender, destination, msg.as_string()) 
    finally: 
     conn.quit() 

except Exception, exc: 
    sys.exit("mail failed; %s" % str(exc)) # give a error message 
+1

@Vincent:mail failed; 'module'對象沒有屬性'SSLFakeSocket' - 使用Gmail :( – RadiantHex 2010-04-26 09:08:21

+0

這聽起來像是一個版本或導入問題,以幫助追蹤:您運行的是什麼版本的Python? - 您是否需要連接到您的SMTP服務器SSL(如果是的話,你是如上導入ssmtplib)? 你可以直接從python交互式導入smtplib,如果有,是否有smtplib.SSLFakeSocket類定義? 希望我可以幫到 – 2010-04-28 11:22:20

6

主要疑難雜症我看到的是,你不處理任何錯誤:的.login()和.sendmail()都已經證明,他們可以拋出異常,而且好像.connect()必須有某種方式表示它無法連接 - 可能是底層套接字代碼拋出的異常。

3

您應該確保以正確格式格式化日期 - RFC2822

5

確保您沒有任何阻止SMTP的防火牆。我第一次嘗試發送電子郵件時,Windows防火牆和McAfee都阻止了它 - 永遠找不到它們。

20

另外,如果你想用TLS做smtp認證而不是SSL,那麼你只需要更改端口(使用587)並執行smtp.starttls()。這對我有效:

... 
smtp.connect('YOUR.MAIL.SERVER', 587) 
smtp.ehlo() 
smtp.starttls() 
smtp.ehlo() 
smtp.login('[email protected]', 'PASSWORD') 
... 
5

這是怎麼回事?

import smtplib 

SERVER = "localhost" 

FROM = "[email protected]" 
TO = ["[email protected]"] # must be a list 

SUBJECT = "Hello!" 

TEXT = "This message was sent with Python's smtplib." 

# Prepare actual message 

message = """\ 
From: %s 
To: %s 
Subject: %s 

%s 
""" % (FROM, ", ".join(TO), SUBJECT, TEXT) 

# Send the mail 

server = smtplib.SMTP(SERVER) 
server.sendmail(FROM, TO, message) 
server.quit() 
67

的方法我經常使用...沒有太大的不同,但一點點

import smtplib 
from email.MIMEMultipart import MIMEMultipart 
from email.MIMEText import MIMEText 

msg = MIMEMultipart() 
msg['From'] = '[email protected]' 
msg['To'] = '[email protected]' 
msg['Subject'] = 'simple email in python' 
message = 'here is the email' 
msg.attach(MIMEText(message)) 

mailserver = smtplib.SMTP('smtp.gmail.com',587) 
# identify ourselves to smtp gmail client 
mailserver.ehlo() 
# secure our email with tls encryption 
mailserver.starttls() 
# re-identify ourselves as an encrypted connection 
mailserver.ehlo() 
mailserver.login('[email protected]', 'mypassword') 

mailserver.sendmail('[email protected]','[email protected]',msg.as_string()) 

mailserver.quit() 

就是這樣

5

下面的代碼是爲我工作的罰款:

import smtplib 

to = '[email protected]' 
gmail_user = '[email protected]' 
gmail_pwd = 'yourpassword' 
smtpserver = smtplib.SMTP("smtp.gmail.com",587) 
smtpserver.ehlo() 
smtpserver.starttls() 
smtpserver.ehlo() # extra characters to permit edit 
smtpserver.login(gmail_user, gmail_pwd) 
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n' 
print header 
msg = header + '\n this is test msg from mkyong.com \n\n' 
smtpserver.sendmail(gmail_user, to, msg) 
print 'done!' 
smtpserver.quit() 

Ref:http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/

2

查看所有這些lenghty答案?請允許我通過幾行完成所有內容來自我宣傳。

導入和連接:

import yagmail 
yag = yagmail.SMTP('[email protected]', host = 'YOUR.MAIL.SERVER', port = 26) 

然後,它只是一個班輪:

yag.send('[email protected]', 'hello', 'Hello\nThis is a mail from your server\n\nBye\n') 

它實際上將關閉,當它超出範圍(或可手動關閉)。此外,它將允許您在您的鑰匙圈註冊您的用戶名,這樣您就不必在腳本中寫出您的密碼(在寫入yagmail之前,真的讓我困擾!)

對於包裝/安裝,提示和技巧請看看gitpip,可用於Python 2和3.