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

时间:2014-07-30 12:42:59

标签: python email imap google-api-python-client

我遇到此问题,我需要定期检查Gmail帐户并将主题添加到没有主题的电子邮件中。我目前的方法非常hacky,我希望有更多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 个答案:

答案 0 :(得分:1)

没有更好的方法。 IMAP中的消息是不可变的 - 客户端可以无限期地缓存它们。还有一些邮件已签名,这些日子已经过了很多,而且您的更改已likely breaks the signatures