Setting Return-Path with Python sendmail for a MIME message

5.8k Views Asked by At

Hi would like to set the "Return-Path" header for a MIME message I send with Python. Basically, I tried something like this :

message = MIMEMultipart()
message.add_header("Return-Path", "[email protected]")
#...

smtplib.SMTP().sendmail(from, to, message.as_string())

The message I receive have its "Return-Path" header set to the same content as the "From" one, even if I explicitly add "Return-Path" header.

How can I set "Return-Path" header for a MIME message sent through smtplib's sendmail in Python ?

Thanks in advance.

1

There are 1 best solutions below

3
On BEST ANSWER

Return-Path is set by the SMTP protocol, it's not derived from the message itself. It'll be the Envelope From address is most setups.

The proper way to accomplish this is:

msg = email.message_from_string('\n'.join([
    'To: [email protected]',
    'From: [email protected]',
    'Subject: test email',
    '',
    'Just testing'
]))
smtp = smtplib.SMTP()
smtp.connect()
smtp.sendmail('[email protected]', '[email protected]', msg.as_string())