在Python中接收和发送邮件
我怎么能在Python中收发邮件呢?就像一个“邮件服务器”。
我想做一个应用程序,它可以监听是否收到发给foo@bar.domain.com的邮件,并且可以回复发件人一封邮件。
我能否全部用Python来实现这个功能?使用第三方库会更好些吗?
10 个回答
12
我觉得用Python写一个真正的邮件服务器并不是个好主意。虽然这确实是可行的(可以看看mcrute和Manuel Ceron的帖子了解更多细节),但想想一个真正的邮件服务器需要处理的事情,比如排队、重发、处理垃圾邮件等等,这可真是个大工程。
你应该更详细地说明你的需求。如果你只是想对收到的邮件做出反应,我建议你配置邮件服务器,让它在收到邮件时调用一个程序。这个程序可以做任何事情,比如更新数据库、创建文件,或者和另一个Python程序交流。
要从邮件服务器调用一个任意的程序,你有几种选择:
- 对于sendmail和Postfix,可以在
~/.forward
文件中写入"|/path/to/program"
- 如果你使用procmail,可以在配方动作中写
|path/to/program
- 当然还有很多其他的选择
19
找到了一个很有用的例子,教你怎么通过IMAP连接来读取邮件:
Python — imaplib使用IMAP连接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
24
这里有一个非常简单的例子:
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模块的文档。