使用 Python 的 smtplib 接收 Gmail 的回复

9

好的,我正在研究一种系统,可以通过短信消息在我的计算机上启动操作。我已经成功发送了最初的消息:

import smtplib  

fromAdd = 'GmailFrom'  
toAdd  = 'SMSTo'  
msg = 'Options \nH - Help \nT - Terminal'  

username = 'GMail'  
password = 'Pass'  

server = smtplib.SMTP('smtp.gmail.com:587')  
server.starttls()  
server.login(username , password)  
server.sendmail(fromAdd , toAdd , msg)  
server.quit()

我只需要知道如何等待回复或从Gmail本身获取回复,然后将其存储在变量中以供后续函数使用。
3个回答

17

发送电子邮件时,应该使用POP3或IMAP,而不是SMTP(后者更可取)。 以下是使用SMTP的示例(代码不是我的,请参考下面的网址以获取更多信息):

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

result, data = mail.fetch(latest_email_id, "(RFC822)") # fetch the email body (RFC822) for the given ID

raw_email = data[0][1] # here's the body, which is raw text of the whole email
# including headers and alternate payloads

这里无耻地盗取


1

我建议您使用这个新的库https://github.com/charlierguo/gmail

一个Pythonic接口到谷歌的GMail,具备所有你需要的工具。搜索、阅读和发送多部分邮件,归档,标记为已读/未读,删除邮件,以及管理标签。

用法

from gmail import Gmail

g = Gmail()
g.login(username, password)

#get all emails
mails = g.inbox().mail() 
# or if you just want your unread mails
mails = g.inbox().mail(unread=True, from="youradress@gmail.com")

g.logout()

优秀的库但不支持Python3。 - BoppreH

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接