0

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

Prudhvi
  • 1
  • 1
  • It looks maybe like Exchange is trying to duplicate suppression of some sort, potentially based on the Message-ID? Forwarding like a client does it will potentially require a lot more parsing and reformatting than you're prepared to do. You could create a new message and attach the original message as a message/rfc822 attachment, if your viewer can handle that. (This is known as 'Forward as Attachment' in some clients) – Max Apr 04 '19 at 21:51
  • Thank you, Max. I've started to work on creating a new email and parsing the body and headers from original message, since I've posted the question here. Any suggestions on what steps of parsing and reformatting you think can help? – Prudhvi Apr 09 '19 at 00:36

0 Answers0