【问题标题】:What is a better way to edit email subjects什么是编辑电子邮件主题的更好方法
【发布时间】:2014-07-30 12:42:59
【问题描述】:

我遇到了这个问题,我需要定期检查 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 来执行此操作。

【问题讨论】:

  • 你可以使用 imaplib 的 append 重新上传消息而不使用 smtp。

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


【解决方案1】:

没有更好的方法。 IMAP 中的消息是不可变的——客户端可以无限期地缓存它们。还有一些消息也被签名了,这些天不少,你的更改likely breaks the signatures

【讨论】:

  • 除非他可以使用 APPEND 上传更改消息,而不是通过 SMTP 重新发送。
  • 他可以使用APPEND,还有其他一些小的改进。例如,他的搜索测试是“主题包含空字符串的消息”。但问题是关于编辑消息。我怀疑适当的解决方案将涉及例如设置 gmail 标签。
  • @arnt subject typ, data = mail.uid('search', None, '(HEADER Subject "")') 现在只是一个小技巧,但设置 gmail 标签很好用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-23
  • 1970-01-01
  • 2017-06-06
  • 2014-10-02
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
相关资源
最近更新 更多