我认为您出错的部分是如何替换邮件中的标头,而且您无需复制邮件,因此,您可以从获取的原始数据中创建邮件后直接对其进行操作从IMAP服务器。
您确实省略了一些细节,所以这是我完整的解决方案,其中阐明了所有细节。请注意,我将SMTP连接置于STARTTLS模式,因为我需要这样做,并且请注意,我已经将IMAP阶段和SMTP阶段彼此分离了。也许您认为更改消息会以某种方式在IMAP服务器上对其进行更改?如果这样做了,这应该清楚地告诉您不会发生这种情况。
import smtplib, imaplib, emailimap_host = "mail.example.com"smtp_host = "mail.example.com"smtp_port = 587user = "xyz"passwd = "xyz"msgid = 7from_addr = "from.me@example.com"to_addr = "to.you@example.com"# open IMAP connection and fetch message with id msgid# store message data in email_dataclient = imaplib.IMAP4(imap_host)client.login(user, passwd)client.select('INBOX')status, data = client.fetch(msgid, "(RFC822)")email_data = data[0][1]client.close()client.logout()# create a Message instance from the email datamessage = email.message_from_string(email_data)# replace headers (could do other processing here)message.replace_header("From", from_addr)message.replace_header("To", to_addr)# open authenticated SMTP connection and send message with# specified envelope from and to addressessmtp = smtplib.SMTP(smtp_host, smtp_port)smtp.starttls()smtp.login(user, passwd)smtp.sendmail(from_addr, to_addr, message.as_string())smtp.quit()
希望即使这个答案来得很晚也能有所帮助。