smtp mail with attachment

Steve Holden sholden at holdenweb.com
Tue Feb 6 09:20:53 EST 2001


"Scott Hathaway" <slhath at home.com.nospam> wrote in message
news:n6Tf6.5629$tv5.438444 at news.flash.net...
> How do I send an email with an attachment with python (I need a cross
> platform solution for Windows and Unix)?
>
> Thanks,
> Scott
>
>
Scott:

There are several ways you could do this, depending on your setup.
Basically:

1.    Generate the email with attachment; then

2.    Send it out.

The first step can be done with several libraries. I myself frequently use
the mimecntl module, available from the Vaults of Parnassus, in which you
would do something like the following:

        f = mimecntl.MIME_document("", type='text/plain')
        f.write("""Dear Customer,

Thank you for your request for services. We have performed these
services, and attach our invoice accordingly.

Sincerely
Holden Web""")
        rtf = mimecntl.MIME_recoder()
        inf = open("Invoice.rtf", "rb")
        rtfstream = inf.read()
        rtf.write(rtfstream)
        rtf['content-type'] = mimecntl.MIMEField('content-type',
'application/rtf')
        rtf['content-length'] = mimecntl.MIMEField('content-length',
len(rtfstream))
        rtf['content-disposition'] =
mimecntl.MIMEField('content-disposition',
                        'attachment',
                        filename=attachname)
        rtf = rtf.encode('base64')
        #
        # Wrap the message, and its attachment, in a single MIME envelope
        #
        msg = mimecntl.MIME_document( (f, rtf),
                From="sholden at holdenweb.com",
                To="Lucky.Client at clientorganization.com",
                Subject = 'Services Invoice for You')

The second step would be to use smtplib to send the mail out via your local
mail system (presumably the same one as you configure your mail agent to use
for sending). This would go something like:

    smtp = smtplib.SMTP("your.mail.host")
    smtp.sendmail("sholden at holdenweb.com",
         "Lucky.Client at clientorganization.com", msg.dump())
    smtp.quit()

There are many ways to skin this particular cat. You probably also want to
take a look at the mimetools and rfc822 modules, which are a part of the
standard distribution, and can also cope with what you want to do.

Note that this code has been cut and farily extensively modified from a
working program which sends invoices out by e-mail (for a client), so I
cannot guarantee its integrity. I think it should give you some ideas,
though.

regards
 Steve





More information about the Python-list mailing list