我正在尝试根据以下标准回复电子邮件:
扫描收件箱看不见的邮件与特定的主题内容,如果有邮件满足这些条件,然后:发送回回复消息给发件人说"某事",如果这些条件不满足,然后发送回回复消息给发件人说"某事"。
这是我目前想到的:
import imaplib
import email
import smtplib
username = 'sample@gmail.com'
password = 'xxxx'
imap_server = imaplib.IMAP4_SSL('smtp.gmail.com')
imap_server.login(username, password)
imap_server.select('INBOX')
result, data = imap_server.search(None, '(UNSEEN)')
email_ids = data[0].split()
for email_id in email_ids:
result, data = imap_server.fetch(email_id, "(RFC822)")
raw_email = data[0][1]
email_message = email.message_from_bytes(raw_email)
subject = email_message["Subject"]
if subject == "SOME SPECIFIC CONTENT":
reply = email.message.EmailMessage()
reply["To"] = email_message["From"]
reply["Subject"] = "Re: " + email_message["Subject"]
reply["In_Reply-To"] = email_message["From"]
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(username, reply["In_Reply-To"], 'Subject: Criteria metnnThank you.')
server.quit()
else:
reply = email.message.EmailMessage()
reply['To'] = email_message['From']
reply['Subject'] = "RE:" + email_message['Subject']
reply["In_Reply-To"] = email_message["From"]
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login(username, password)
server.sendmail(username, reply["In_Reply-To"], 'Subject: Criteria not metnThank you.')
print('Sending email')
server.quit()
imap_server.close()
它发送电子邮件,但没有所需的线程,只是发送一个新的电子邮件,而不是实际回复发件人。
任何关于如何修改代码的建议,所以它实际上发送一个回复与所需的线程?
提前谢谢你。
就像评论提到的那样,您应该使用原始消息的message - id,而不是发送者地址。
同时,您应该服从Reply-To:
并添加References:
。
reply = email.message.EmailMessage()
reply["To"] = email_message["Reply-To"] or email_message["From"]
reply["Subject"] = "Re: " + email_message["Subject"]
reply["In_Reply-To"] = email_message["Message-Id"]
reply["References"] = (email_message["References"] or "") + " " + email_message["Message-Id"]
正确地说,References:
标题应该从中间修剪,如果它太长。
一些供应商有他们自己的非标准线程扩展;特别是,Microsoft的Thread-Id:
等标头可能最好忽略。