I'm trying to read an email, get the headers (from, to, cc, subject) and body of an email and forward the email (forwarding email will vary based on the from).
I've referenced the post to write my code. I was able to forward few emails, but few fail.
import smtplib, imaplib, email
imap_host = "imap-mail.outlook.com"
smtp_host = "smtp-mail.outlook.com"
imap_port = 993
smtp_port = 587
user = "aaa@bbb.com"
passwd = "****"
### Testing random emails using msgid
msgid = 5000
from_addr = "aaa@bbb.com"
to_addr = "ccc@ddd.com"
client = imaplib.IMAP4_SSL(imap_host, imap_port)
client.login(user, passwd)
client.select('INBOX')
status, data = client.fetch(str(msgid), "(RFC822)") #(RFC822) or (UID BODY[TEXT])
email_data = data[0][1]
client.close()
client.logout()
message = email.message_from_bytes(email_data)
message.add_header('From', from_addr) #also tried replace_header
message.replace_header('To', to_addr)
smtp = smtplib.SMTP(smtp_host, smtp_port)
smtp.starttls()
smtp.login(user, passwd)
smtp.sendmail(from_addr, to_addr, message.as_string())
# smtp.send_message(message, from_addr, to_addr)
smtp.quit()
Here is the error, I receive: 554, b'5.2.0 STOREDRV.Submission.Exception:StoragePermanentException.MapiExceptionDuplicateDelivery; Failed to process message due to a permanent exception with message Cannot get ID from name.
Also, any suggestions on how to make the email look like a forward i.e., include the headers of the original email in the body of the forward (as if forwarded from web outlook or the outlook app). Thanks