Forwarding messages with the email package

Gerhard Häring gh_pythonlist at gmx.de
Sat Mar 2 12:43:35 EST 2002


Le 04/02/02 à 05:17, Gerhard Häring écrivit:
> I'm having some problems with the new email package in Python 2.2. I
> guess the reason is that I don't really understand MIME and I fear my
> head will explode when I try to make sense of the source code of the
> email package.
> 
> What I'm trying to do is forward an email message with MIME. I. e. not
> inline. I'm trying to duplicate what my MUA does. It creates a
> multipart/mixed MIME doc with a text/plain part and a message/rfc822
> part, that contains the email to forward. So, my current code is:
> [snip buggy code]

Hello Gerhard, maybe you'll find the following code useful:

#!/usr/bin/env python2.2
#
# Written by: Gerhard Häring (gerhard at bigfoot.de)
# License: none/public domain

import sys, os, smtplib, email
from email.Message import Message
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEMessage import MIMEMessage

class Config:
    """Settings for Spamcop reports.
    You must at least change SUBMISSION_ADDRESS to match the one you got from
    Spamcop. You also need to provide a valid SMTP server address, localhost is
    just fine on many *nix systems."""
    SUBMISSION_ADDRESS = "Spamcop <submit.abcdefghijklmnop at spam.spamcop.net>"
    SMTP_SERVER = "localhost"
    MY_ADDRESS = "you at yournetwork.net"
    SUBJECT = "Spam report"
    BODY = "Dear Spamcop! Please analyze the following spam."

def strip_spamassassin_markup(spam):
    infile, outfile = os.popen2("spamassassin -d -")
    infile.write(spam)
    infile.close()
    return outfile.read()

def main():
    forwarded_mail = strip_spamassassin_markup(sys.stdin.read())

    me = Config.MY_ADDRESS
    to = [Config.SUBMISSION_ADDRESS]
    message = MIMEBase("multipart", "mixed")
    message["Subject"] = Config.SUBJECT
    message["From"] = Config.MY_ADDRESS
    message["To"] = ", ".join(to)

    message.attach(MIMEText(Config.BODY))

    rfcmessage = MIMEBase("message", "rfc822")
    message_to_forward = email.message_from_string(forwarded_mail)
    rfcmessage.attach(message_to_forward)
    message.attach(rfcmessage)

    smtpserver = smtplib.SMTP(Config.SMTP_SERVER)
    smtpserver.sendmail(me, to, message.as_string(unixfrom=0))
    smtpserver.close() 

if __name__ == "__main__":
    main()

Hmm, maybe I should submit a patch to the docs of the email module.

Gerhard
-- 
This sig powered by Python!
Außentemperatur in München: 2.4 °C      Wind: 3.4 m/s




More information about the Python-list mailing list