I've tried with no conclusions to resend emails with Python.
Once I've logged in SMTP and IMAP with TLS, this is what I have written:
status, data = self._imapserver.fetch(id, "(RFC822)")
email_data = data[0][1]
# create a Message instance from the email data
message = email.message_from_string(email_data)
# replace headers (could do other processing here)
message.replace_header("From", '[email protected]')
message.replace_header("To", '[email protected]')
self._smtpserver.sendmail('[email protected]', '[email protected]', message.as_string())
But the problem is that the variable data doesn't catch the information from the email, even if the ID is the one I need. It tells me:
b'The specified message set is invalid.'
How can I transfer an email with Python?
CodePudding user response:
Like the error message says, whatever you have in id
is invalid. We don't know what you put there, so all we can tell you is what's already in the error message.
(Also, probably don't use id
as a variable name, as you will shadow the built-in function with the same name.)
There are additional bugs further on in your code; you need to use message_from_bytes
if you want to parse it, though there is really no need to replace the headers just to resend it.
status, data = self._imapserver.fetch(correct_id, "(RFC822)")
self._smtpserver.sendmail('[email protected]', '[email protected]', data[0][1])
If you want to parse the message, you should perhaps add a policy
argument; this selects the modern EmailMessage
API which was introduced in Python 3.6.
from email.policy import default
...
message = email.message_from_bytes(data[0][1], policy=default)
message["From"] = "[email protected]"
message["To"] = "[email protected]"
self._smtpserver.send_message(message)
The send_message
method is an addition to the new API. If the message could contain other recipient headers like Cc:
, Bcc:
etc, perhaps using the good old sendmail
method would be better, as it ignores the message's headers entirely.