Python、IMAP和GMail。将邮件标记为已读

9 投票
3 回答
21792 浏览
提问于 2025-04-15 19:12

我有一个Python脚本,它需要获取未读消息,处理这些消息,然后标记为已读。

我在登录后这样做:

    typ, data = self.server.imap_server.search(None, '(UNSEEN)')

    for num in data[0].split():
        print "Mensage " + str(num) + " mark"
        self.server.imap_server.store(num, '+FLAGS', '(SEEN)')

第一个问题是,搜索返回的是所有消息,而不仅仅是未读的。

第二个问题是,消息没有被标记为已读。

有人能帮我解决这个问题吗?

谢谢!

3 个回答

2

我对imaplib不是很熟悉,不过我用imapclient模块实现得很好。

import imapclient,pyzmail,html2text
from backports import ssl
context=ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

iobj=imapclient.IMAPClient('outlook.office365.com', ssl=True, ssl_context=context)
iobj.login(uname,pwd)# provide your username and password
iobj.select_folder('INBOX',readonly=True)# Selecting Inbox.

unread=iobj.search('UNSEEN')# Selecting Unread messages, you can add more search criteria here to suit your purpose.'FROM', 'SINCE' etc.
print('There are: ',len(unread),' UNREAD emails')

for i in unread:

    mail=iobj.fetch(i,['BODY[]'])#I'm fetching the body of the email here.
    mcontent=pyzmail.PyzMessage.factory(mail[i][b'BODY[]'])#This returns the email content in HTML format
    subject=mcontent.get_subject()# You might not need this             
    receiver_name,receiver_email=mcontent.get_address('from')
    mail_body=html2text.html2text(mcontent.html_part.get_payload().decode(mcontent.html_part.charset))# This returns the email content as text that you can easily relate with.

假设我想查看未读邮件,回复发件人,并把邮件标记为已读。我会在这里调用smtp函数来写回复邮件并发送。

import smtplib
smtpobj=smtplib.SMTP('smtp.office365.com',587)
smtpobj.starttls()
smtpobj.login(uname,pwd)# Your username and password goes here.
sub='Subject: '+str(subject)+'\n\n'# Subject of your reply
msg='Thanks for your email! You're qualified for the next round' #Some random reply :(
fullmsg=sub+new_result
smtpobj.sendmail(uname,test,fullmsg)# This sends the email. 
iobj.set_flags(i,['\\Seen','\\Answered'])# This marks the email as read and adds the answered flag
iobj.append('Sent Items', fullmsg)# This puts a copy of your reply in your Sent Items.

iobj.logout()
smtpobj.logout()

希望这对你有帮助。

4

我觉得这些标志的名字应该以反斜杠开头,比如说:\SEEN

20

在编程中,有时候我们需要处理一些数据,比如从一个地方获取数据,然后在另一个地方使用这些数据。这个过程就像是把水从一个水桶倒到另一个水桶里。

有些时候,我们会遇到一些问题,比如数据的格式不对,或者数据不完整。这就像是水桶里有个洞,水会漏掉,导致我们不能得到想要的结果。

为了避免这些问题,我们可以使用一些工具和方法来检查和处理数据。这样可以确保我们得到的水(数据)是干净的、完整的,能够顺利地倒到另一个水桶里。

总之,处理数据就像是管理水流,我们需要注意每一个环节,确保最终能得到我们想要的结果。

import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com', '993')
obj.login('user', 'password')
obj.select('Inbox')   <--- it will select inbox
typ ,data = obj.search(None,'UnSeen')
obj.store(data[0].replace(' ',','),'+FLAGS','\Seen')

撰写回答