Python 编辑电子邮件主题的更好方法是什么
我有这个问题,我需要定期检查一个Gmail帐户,并在没有主题的电子邮件中添加主题。我目前的方法非常粗糙,我希望有更多IMAP/GoogleAPI知识的人能提出更好的方法 现在,我的python脚本将检查Gmail中的消息和没有主题的电子邮件,它将创建消息的副本并重新发送(返回到自身)。以下是代码(不包括身份验证:Python 编辑电子邮件主题的更好方法是什么,python,email,imap,google-api-python-client,Python,Email,Imap,Google Api Python Client,我有这个问题,我需要定期检查一个Gmail帐户,并在没有主题的电子邮件中添加主题。我目前的方法非常粗糙,我希望有更多IMAP/GoogleAPI知识的人能提出更好的方法 现在,我的python脚本将检查Gmail中的消息和没有主题的电子邮件,它将创建消息的副本并重新发送(返回到自身)。以下是代码(不包括身份验证: # Select the inbox mail.select() # Get the UID of each email in the inbox with "" subject
# 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有更好的方法来做到这一点,而不需要重新发送消息。没有更好的方法了。IMAP中的消息是不可变的-客户端可能会无限期地缓存它们。有些消息也会被签名,最近有好几天,还有您的更改。您可以使用imaplib的append可在不使用smtp的情况下重新上载邮件。但他可以使用APPEND上载更改邮件,而不是通过smtp重新发送。他可以使用APPEND,还有其他一些小的改进。他的搜索测试是“主题包含空字符串的邮件”例如,但问题是关于编辑邮件的。我怀疑一个合适的解决方案将包括设置gmail标签。@arnt
subject-typ,data=mail.uid('search',None',(HEADER-subject'))
目前只是一个小技巧,但设置gmail标签是一个不错的选择