如何在python中收發電子郵件?各種「郵件服務器」。在python中接收和發送電子郵件
我正在研究製作一個應用程序,用於偵聽是否收到發給[email protected]的電子郵件,並向發件人發送電子郵件。
現在,我能夠在python中做到這一切,最好是使用第三方庫嗎?
如何在python中收發電子郵件?各種「郵件服務器」。在python中接收和發送電子郵件
我正在研究製作一個應用程序,用於偵聽是否收到發給[email protected]的電子郵件,並向發件人發送電子郵件。
現在,我能夠在python中做到這一切,最好是使用第三方庫嗎?
這是一個很簡單的例子:
import smtplib
server = 'mail.server.com'
user = ''
password = ''
recipients = ['[email protected]', '[email protected]']
sender = '[email protected]'
message = 'Hello World'
session = smtplib.SMTP(server)
# if your SMTP server doesn't need authentications,
# you don't need the following line:
session.login(user, password)
session.sendmail(sender, recipients, message)
更多選項,錯誤處理,等等,看看smtplib module documentation。
是的,你可以用內置的庫來做幾乎所有的事情。在這裏搜索尋找標籤[python]
和[email]
,你會看到它是如何完成的。
poplib和smtplib將在開發您的應用程序時成爲您的朋友。
Python有一個SMTPD模塊,可以幫助您編寫服務器。您可能還希望SMTP模塊執行重新發送。至少從版本2.3開始,這兩個模塊都在標準庫中。
根據您發送的郵件數量,您可能想要使用像postifx或sendmail(* nix系統)這樣的真實郵件服務器來查看這兩種程序都能夠根據電子郵件地址。
我不認爲這將是用Python語言編寫一個真正的郵件服務器是一個好主意。這當然是可能的(請參閱mcrute和Manuel Ceron的帖子以獲得詳細信息),但是當您想到真正的郵件服務器必須處理的所有事情(排隊,重傳,處理垃圾郵件等)時,這是很多工作。
你應該更詳細地解釋你需要什麼。如果您只想對收到的電子郵件做出反應,我會建議配置郵件服務器在收到電子郵件時調用程序。這個程序可以做它想做的事情(更新數據庫,創建文件,與另一個Python程序交談)。
要調用從郵件服務器中的任意程序,你有幾種選擇:
~/.forward
含"|/path/to/program"
|path/to/program
找到一個有用的例子來通過使用IMAP連接來閱讀電子郵件:
Python — imaplib IMAP example with Gmail
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('[email protected]', 'mypassword')
mail.list()
# Out: list of "folders" aka labels in gmail.
mail.select("inbox") # connect to inbox.
result, data = mail.search(None, "ALL")
ids = data[0] # data is a list.
id_list = ids.split() # ids is a space separated string
latest_email_id = id_list[-1] # get the latest
# fetch the email body (RFC822) for the given ID
result, data = mail.fetch(latest_email_id, "(RFC822)")
raw_email = data[0][1] # here's the body, which is raw text of the whole email
# including headers and alternate payloads
要做到這一點是創建在python接收使用imaplib2
下面的郵件窗口服務的最佳方式是一個示例python腳本做same.You能通過在命令行「python THENAMEOFYOURSCRIPTFILE.py install」上運行以下命令來安裝此腳本作爲Windows服務運行。
import win32service
import win32event
import servicemanager
import socket
import imaplib2, time
from threading import *
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import datetime
import email
class Idler(object):
def __init__(self, conn):
self.thread = Thread(target=self.idle)
self.M = conn
self.event = Event()
def start(self):
self.thread.start()
def stop(self):
self.event.set()
def join(self):
self.thread.join()
def idle(self):
while True:
if self.event.isSet():
return
self.needsync = False
def callback(args):
if not self.event.isSet():
self.needsync = True
self.event.set()
self.M.idle(callback=callback)
self.event.wait()
if self.needsync:
self.event.clear()
self.dosync()
def dosync(self):
#DO SOMETHING HERE WHEN YOU RECEIVE YOUR EMAIL
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "receiveemail"
_svc_display_name_ = "receiveemail"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
M = imaplib2.IMAP4_SSL("imap.gmail.com", 993)
M.login("YourID", "password")
M.select("INBOX")
idler = Idler(M)
idler.start()
while True:
time.sleep(1*60)
idler.stop()
idler.join()
M.close()
M.logout()
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
覆蓋發送部分,如果你能使用smptd所模塊,這將是一個偉大的答案 – Jay 2008-12-08 03:23:41
注意這是很遠的一個真實的電子郵件服務器,因爲大多數真正的偵聽新郵件添加快速片段工作(排隊和重傳)由'mail.server.com'完成,而不是由Python程序完成。 – bortzmeyer 2008-12-08 12:20:49
你是對的。它離真正的郵件服務器非常遠。 – 2008-12-08 18:32:19