使用smtplib - Python接收Gmail的回复 [英] Receive replies from Gmail with smtplib - Python

查看:161
本文介绍了使用smtplib - Python接收Gmail的回复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在研究一种系统,以便我可以使用短信开始在我的计算机上进行操作。

 导入smtplib 

fromAdd ='GmailFrom'$我可以让它发送最初的消息: b $ b toAdd ='SMSTo'
msg ='选项\\\
H - 帮助\\\
T - 终端'

用户名='GMail'
密码='通过'

server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(用户名,密码)
服务器。 sendmail(fromAdd,toAdd,msg)
server.quit()

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

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

  import imaplib 
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('myusername@gmail.com','mypassword')
mail.list()
#Out:gmail中的文件夹(也就是标签)列表。
mail.select(收件箱)#连接到收件箱。

结果,data = mail.search(无,ALL)

ids = data [0]#data是一个列表。
id_list = ids.split()#ids是一个空格分隔的字符串
latest_email_id = id_list [-1]#获取最新的

结果,data = mail.fetch(latest_email_id ,(RFC822))#获取给定ID

的电子邮件正文(RFC822)raw_email = data [0] [1]#这是正文,它是整个电子邮件的原始文本
#包括标题和备用有效载荷

无耻地从此处


Ok, I am working on a type of system so that I can start operations on my computer with sms messages. I can get it to send the initial message:

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()

I just need to know how to wait for the reply or pull the reply from Gmail itself, then store it in a variable for later functions.

解决方案

Instead of SMTP which is used for sending emails, you should use either POP3 or IMAP (the latter is preferable). Example of using SMTP (the code is not mine, see the url below for more info):

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

Shamelessly stolen from here

这篇关于使用smtplib - Python接收Gmail的回复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆