用python接收和发送电子邮件

我怎样才能收到和发送电子邮件在Python? 一个“邮件服务器”的种类。

我正在研究制作一个应用程序,以侦听是否收到发给foo@bar.domain.com的电子邮件,并向发件人发送电子邮件。

现在,我能够做到这一切在Python中,是否最好使用第三方库?

这是一个非常简单的例子:

import smtplib server = 'mail.server.com' user = '' password = '' recipients = ['user@mail.com', 'other@mail.com'] sender = 'you@mail.com' 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) 

有关更多选项,error handling等,请查看smtplib模块文档 。

我不认为用Python写一个真正的邮件服务器是个好主意。 这当然是可能的(请参阅mcrute和Manuel Ceron的post以获得详细信息),但是当您想到真正的邮件服务器必须处理的所有事情(排队,重发,处理垃圾邮件等)时,这是很多工作。

你应该更详细地解释你需要什么。 如果你只是想对收到的电子邮件做出反应,我会build议configuration邮件服务器在收到邮件时调用一个程序。 这个程序可以做它想做的事情(更新数据库,创build一个文件,和另一个Python程序交谈)。

要从邮件服务器调用任意程序,您有几个select:

  1. 对于sendmail和Postfix,包含"|/path/to/program"~/.forward
  2. 如果使用procmail, |path/to/program的配方动作
  3. 当然还有许多其他的

通过使用IMAP连接,find一个阅读电子邮件的有用示例:

Python – 使用Gmail的imaplib IMAP示例

 import imaplib mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login('myusername@gmail.com', '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有一个SMTPD模块,可以帮助你编写一个服务器。 您可能还希望SMTP模块执行重新发送。 至less从版本2.3开始,这两个模块都在标准库中。

poplib和smtplib将在开发您的应用程序时成为您的朋友。

发送部分已被覆盖,为接收您可以使用POP或IMAP

是的,你可以用内置的库来做很多事情。 在这里做一个search寻找标签[python][email] ,你会看到它是如何完成的。

根据您发送的邮件数量,您可能需要使用像postifx或sendmail(* nix系统)这样的真实邮件服务器进行研究。这两个程序都能够根据电子邮件地址将收到的邮件发送到某个程序。

最好的办法是在python中创build一个windows服务,使用imaplib2接收邮件

下面是一个python脚本示例。您可以通过在命令行“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)