Skip to main content
 首页 » 编程设计

python之搜索电子邮件并打开退订链接

2024年12月31日35yyy_WW

我目前正在做一个来自 Automate the Boring Stuff 的项目,我应该编写一个程序来扫描我的电子邮件并找到取消订阅链接并在浏览器中打开它们。

这是我现在拥有的代码,但我不确定为什么它无法在新浏览器中打开任何电子邮件。任何帮助将不胜感激。

#! Python3 
# Write a program that scans through your email account,finds all the 
# unsubscribe links in all your emails, and automatically opens them in a browser. 
 
import imapclient 
import pyzmail 
import webbrowser 
import bs4 
 
# User input 
user_email = input('Enter your email: ') 
user_pass = input('Enter your password: ') 
 
# Connects to IMAP Server 
imap_obj = imapclient.IMAPClient('imap.gmail.com', ssl=True) 
imap_obj.login(user_email, user_pass) 
imap_obj.select_folder('INBOX', readonly=True) 
UIDs = imap_obj.gmail_search('after:2018/07/13 before:2018/07/14 unsubscribe') 
raw_messages = imap_obj.fetch(UIDs, ['BODY[]']) 
 
for i in UIDs: 
    message = pyzmail.PyzMessage.factory(raw_messages[i][b'BODY[]']) 
    raw_soup = message.html_part.get_payload().decode(message.html_part.charset) 
    soup = bs4.BeautifulSoup(raw_soup, 'html.parser') 
    for unsub in soup.findAll('a'): 
        print(unsub) 
        break 
        if 'Unsubscribe' in unsub: 
            webbrowser.open(unsub) 
 
imap_obj.logout() 

请您参考如下方法:

您需要检查“Unsubscribe”是否在元素的文本中。 in 不会像您预期的那样在不可迭代的事物上工作(例如 bs4 元素标签)。有点像

    soup = bs4.BeautifulSoup(raw_soup, 'html.parser') 
    for unsub in soup.find_all('a'): 
        print((unsub.text, unsub.get('href'))) 
        if 'unsubscribe' in unsub.text.lower(): 
            webbrowser.open(unsub.get('href')) 

(注意最后一行的unsub.href,你需要访问这些标签的属性,而不是对标签本身的引用)