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 本身提取回复,然后将其存储在变量中以供以后使用。

4

3 回答 3

17

代替用于发送电子邮件的 SMTP,您应该使用 POP3 或 IMAP(后者更可取)。使用 SMTP 的示例(代码不是我的,请参阅下面的 url 了解更多信息):

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

无耻地从这里偷走

于 2013-08-09T22:29:16.327 回答
1

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

Google 的 GMail 的 Pythonic 界面,包含您需要的所有工具。搜索、阅读和发送多部分电子邮件、存档、标记为已读/未读、删除电子邮件和管理标签。

用法

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()
于 2013-08-10T09:31:55.230 回答
1

Uku 的回答看起来很合理。但是,作为一个实用主义者,我将回答一个您没有提出的问题,并建议一个更好的 IMAP 和 SMTP 库。

我自己没有在任何其他项目中使用过这些,所以你需要自己进行评估,但两者都更好用。

IMAP https://github.com/martinrusev/imbox

SMTP: http ://tomekwojcik.github.io/envelopes/

于 2013-08-09T23:11:41.120 回答