编辑邮件主题的更好方法是什么

0 投票
1 回答
1461 浏览
提问于 2025-04-18 15:20

我遇到了一个问题,需要定期检查一个Gmail账户,并给没有主题的邮件添加主题。目前我使用的方法很不靠谱,希望有更懂IMAP或Google API的人能给我推荐一个更好的方法。

现在,我的Python脚本会检查Gmail中的邮件,对于没有主题的邮件,它会复制一份邮件并重新发送(其实是发回给自己)。下面是相关的代码(不包括认证部分):

# Select the inbox 
mail.select()

# Get the UID of each email in the inbox with "" 
subject typ, data = mail.uid('search', None, '(HEADER Subject "")')

# Loop for each of the emails with no subjects 
for email_id in data[0].split():
    print email_id
    # Use the uid and get the email message
    result, message = mail.uid('fetch', email_id, '(RFC822)')
    raw_email = message[0][1]
    email_msg = email.message_from_string(raw_email)
    # Check that the subject is blank
    if email_msg['Subject'] == '':
        print email_msg['From']
        print email_msg['To']
        # Get the email payload
        if email_msg.is_multipart():
            payload = str(email_msg.get_payload()[0])
            # Trim superfluous text from payload
            payload = '\n'.join(payload.split('\n')[3:])
            print payload
        else:
            payload = email_msg.get_payload()
        # Create the new email message
        msg = MIMEMultipart()
        msg['From'] = email_msg['From']
        msg['To'] = email_msg['To']
        msg['Subject'] = 'No Subject Specified'
        msg.attach(MIMEText(payload))
        s = smtplib.SMTP('smtp.brandeis.edu')
        print 'Sending Mail...'
        print msg['To']
        s.sendmail(email_msg['From'], [email_msg['To']], msg.as_string())
        s.quit()

mail.close() 
mail.logout()

我希望能找到一个更好的方法,使用Python的IMAP库或Google API,而不是通过重新发送邮件来实现。

1 个回答

1

没有更好的办法了。在IMAP中,消息是不可改变的——客户端可以无限期地缓存这些消息。而且现在有很多消息是经过签名的,你的修改很可能会破坏这些签名。

撰写回答