email forwarding program

Gerhard Häring gh_pythonlist at gmx.de
Thu Jun 13 22:03:50 EDT 2002


* Matthew Bell <mbell at cs.pitt.edu> [2002-06-13 08:51 -0700]:
> Hi,
> 
> I have a question regarding the email handling
> libraries in Python.  I'm trying to write a
> program that, based on some information it
> extracts from an email, forwards it to another
> person.  I've about figured out imaplib, but
> don't see how I can use it to forward on emails.

Use the email module to construct email messages and the smtplib module
to actually send the message.

This unfinished, but working script is lying around in my src/ dir. It's
for forwarding a message including full headers to SpamCop and shows how
to use the email module to do so.

HTH,

Gerhard

#!/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.CENSORED at spam.spamcop.net>"
    SMTP_SERVER = "localhost"
    MY_ADDRESS = "CENSORED at bigfoot.de"
    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()
-- 
This sig powered by Python!
Außentemperatur in München: 17.3 °C      Wind: 2.0 m/s





More information about the Python-list mailing list