【发布时间】: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