如何在python中接收和发送电子邮件?各种"邮件服务器".
我正在研究制作一个应用程序,听取它是否收到发送到foo@bar.domain.com的电子邮件,并向发件人发送电子邮件.
现在,我能在python中完成所有这些,最好是使用第三方库吗?
Man*_*ron 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)
Run Code Online (Sandbox Code Playgroud)
有关更多选项,错误处理等,请查看smtplib模块文档.
bor*_*yer 13
我不认为用Python编写真正的邮件服务器是个好主意.这当然是可能的(请参阅mcrute和Manuel Ceron的帖子以获取详细信息)但是当您想到真正的邮件服务器必须处理的所有内容(排队,重新传输,处理垃圾邮件等)时,这是很多工作.
您应该更详细地解释您需要什么.如果您只想对收到的电子邮件做出反应,我建议将邮件服务器配置为在收到电子邮件时调用程序.这个程序可以做它想做的事情(更新数据库,创建文件,与另一个Python程序交谈).
要从邮件服务器调用任意程序,您有以下几种选择:
~/.forward
包含"|/path/to/program"
|path/to/program
jak*_*ann 13
通过使用IMAP连接找到了阅读电子邮件的有用示例:
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
Run Code Online (Sandbox Code Playgroud)