4

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", "something@something.com")
#...

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.

Pierre
  • 63
  • 1
  • 4

1 Answers1

4

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: michael@mydomain.com',
    'From: michael@mydomain.com',
    'Subject: test email',
    '',
    'Just testing'
]))
smtp = smtplib.SMTP()
smtp.connect()
smtp.sendmail('something@something.com', 'michael@mydomain.com', msg.as_string())
MikeyB
  • 3,288
  • 1
  • 27
  • 38
  • 1
    This works: "From" address is taken from message and "Return-Path" is taken from "from" argument of smtp.sendmail. Quite odd to me but efficient. Thanks for this, I've never seen an answer about that anywhere. – Pierre Jul 28 '10 at 10:25
  • NOTE THAT "msg" could be anything that smtplib.sendmail can accept, it just have to specify a "From" header. – Pierre Jul 28 '10 at 10:27
  • 1
    It's not really that odd if you know what's going on; Return-Path is a header added by the intermediate (end?) MTAs to reflect the actual sender of the message. Errors/bounces/etc. should go to the Envelope sender, not the address in From:. – MikeyB Jul 28 '10 at 14:02