在python中接收和发送电子邮件

时间:2008-12-08 00:12:25

标签: python email

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

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

现在,我能在python中完成所有这些,最好是使用第三方库吗?

10 个答案:

答案 0 :(得分:23)

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

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)

有关更多选项,错误处理等,请查看smtplib module documentation

答案 1 :(得分:13)

通过使用IMAP连接来找到阅读电子邮件的有用示例:

Python — imaplib IMAP example with Gmail

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

答案 2 :(得分:12)

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

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

要从邮件服务器调用任意程序,您有以下几种选择:

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

答案 3 :(得分:7)

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

答案 4 :(得分:4)

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

答案 5 :(得分:3)

发送部分已涵盖,对于接收,您可以使用popimap

答案 6 :(得分:2)

是的,您可以使用内置库完成所有操作。在此处搜索标记[python][email],您将看到它是如何完成的。

答案 7 :(得分:2)

根据您发送的邮件数量,您可能希望使用postifx或sendmail(* nix系统)这样的真实邮件服务器进行查看。这两个程序都能够将收到的邮件发送到基于电子邮件地址。

答案 8 :(得分:1)

执行此操作的最佳方法是在python中创建一个使用imaplib2接收电子邮件的Windows服务

下面是一个示例python脚本。您可以通过在命令行上运行以下命令来安装此脚本以作为Windows服务运行" python THENAMEOFYOURSCRIPTFILE.py install"。

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)

答案 9 :(得分:0)

您可以使用emailpy

通过pip3 install emailpy安装

import emailpy
manager = emailpy.EmailManager('your email', 'your password')
msg = manager.send(['who you are sending to', 'the other email you are sending to', subject='hello', body='this email is sent from Python', html='<h1>Hello World!</h1>', attachments=['yourfile.txt', 'yourotherfile.py'])
while not msg.sent:
    pass
print('sent')
messages = manager.read()
for message in messages:
    print(message.sender, message.date, message.subject, message.body, message.html, message.attachments)
    for attachment in message.attachments:
        print(attachment.name)
        attachment.download()
相关问题