2008-12-08 77 views
32

如何在python中收发电子邮件?各种“邮件服务器”。在python中接收和发送电子邮件

我正在研究制作一个应用程序,用于侦听是否收到发给[email protected]的电子邮件,并向发件人发送电子邮件。

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

回答

23

这是一个很简单的例子:

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

+2

覆盖发送部分,如果你能使用smptd所模块,这将是一个伟大的答案 – Jay 2008-12-08 03:23:41

+7

注意这是很远的一个真实的电子邮件服务器,因为大多数真正的侦听新邮件添加快速片段工作(排队和重传)由'mail.server.com'完成,而不是由Python程序完成。 – bortzmeyer 2008-12-08 12:20:49

+0

你是对的。它离真正的邮件服务器非常远。 – 2008-12-08 18:32:19

2

是的,你可以用内置的库来做几乎所有的事情。在这里搜索寻找标签[python][email],你会看到它是如何完成的。

4

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

6

Python有一个SMTPD模块,可以帮助您编写服务器。您可能还希望SMTP模块执行重新发送。至少从版本2.3开始,这两个模块都在标准库中。

2

根据您发送的邮件数量,您可能想要使用像postifx或sendmail(* nix系统)这样的真实邮件服务器来查看这两种程序都能够根据电子邮件地址。

3

发送部分已被覆盖,接收,您可以使用popimap

12

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

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

要调用从邮件服务器中的任意程序,你有几种选择:

  1. 要使sendmail和Postfix,一个~/.forward"|/path/to/program"
  2. 如果您使用的procmail的|path/to/program
  3. 配方动作当然还有很多其他的
12

找到一个有用的例子来通过使用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 
1

要做到这一点是创建在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)