使用 smtplib - Python 接收来自 Gmail 的回复

2022-01-23 00:00:00 python smtplib gmail reply

问题描述

好的,我正在开发一种系统,以便我可以通过短信在我的计算机上开始操作.我可以让它发送初始消息:

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

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.


解决方案

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

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

从这里

相关文章