sending mail attachements via python & smtplib

Emile van Sebille emile at fenx.com
Sat Apr 14 02:37:54 EDT 2001


"""
I was looking to do this recently and found this.  Use by invoking
mailFileToUser(user at company.com, fullyQualifiedFileName)

HTH,

--

Emile van Sebille
emile at fenx.com

"""


import string
import MimeWriter
import mimify
import StringIO
from smtplib import SMTP
import base64


# Mails a file to the user in MIME format

# Based upon code by GVR

def mailFileToUser(_userName, _fileName):
    # We are using a string as a temporary file

    outputfp = StringIO.StringIO()

    # Create a MimeWriter object

    w = MimeWriter.MimeWriter(outputfp)
    w.addheader("subject", "Current Invoice Copies")
    w.addheader("MIME-Version", "1.0")
    w.flushheaders()

    # Now we create a plain text segment and write the instructions file
into it

    w.startmultipartbody("mixed")
    instructions = w.nextpart()
    instFile = instructions.startbody("text/plain")
    instructions.flushheaders()
    ###instFile.write(open("./instructions.txt", "r").read())

    # Now we create a base64 encoded segment and write the diary file into
it
    # as an attachment

    subwriter = w.nextpart()
    subwriter.addheader("Content-Transfer-Encoding", "base64")
    subwriter.addheader("Content-Disposition", 'attachment; filename="%s"' %
_fileName)
    f = subwriter.startbody('application/octet-stream; name="%s"' %
_fileName)
    subwriter.flushheaders()
    base64.encode(open('%s' % _fileName, 'r'), f)
    w.lastpart()

    # Next we have to email the mail message to the user

    # the outputfp.getvalue retrieves all the stuff written to the StringIO
file object

    s = SMTP('172.20.7.10')
    s.sendmail("SenderName at sendingCompany.com", _userName,
outputfp.getvalue())
    s.close()

"""
---------
"Rajarshi Guha" <rajarshi at presidency.com> wrote in message
news:9b8jrr$86f9m$1 at ID-82539.news.dfncis.de...
> Hi,
>   using the smtplib module I'm able to send mails froma Python script.
> However I need to send attachements with the mail. I think I have to
mimefy
> the attachement, but I'm not too sure about how to go about it. After
> mimefication how do I add it to the mail?
>
> Could give me a general idea of how to go about this?
>
> TIA,
>
> Rajarshi Guha
> mailto:rajarshi at presidency.com
>
>
"""





More information about the Python-list mailing list