MIME attachments, and alternatives

bill ramsay bill.ramsay at clear.net.nz
Wed Jun 9 10:36:25 CEST 2004


I am writing a program that sends simple text files to a remote

the files have to be in the format textX.dat  where X = numbers in the
range 0 up to 10 depending upon the situation. these files are stored
in a directory called attachments.

The files themselves are single line affairs in ascii.

the files have to be sent in base64.  

the final email has a simple subject line,  to and from addresses,
and the attachments.

so far so good,  I have written the program to do this,  don't laugh
here it comes.

the print statements are just there so that i can follow whats going
on at the moment.


import os
import smtplib
import mimetypes

from email import Encoders
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

def send_dat_files(subject_matter,serial,fromAddr,toAddr):

    base = os.getcwd()
    print base
    attachpath = base+'\\attachments'

    if not os.path.exists(attachpath):
    # Create the enclosing (outer) message

    if subject_matter == 'SU':
        subjectstring = 'KKK_KRDS1_'+serial+'_SU'

    outer = MIMEMultipart()
    outer['Subject'] = subjectstring
    outer['To'] = toAddr
    outer['From'] = fromAddr

    outer.add_header('Content-Description','Remote Management System')
    outer.epilogue = ''

    fileNames=[f for f in os.listdir(attachpath)]
    for fileName in fileNames:
        path = attachpath+'\\'+fileName
        bodytext = f.read()  
        ctype, encoding = mimetypes.guess_type(path)
        maintype, subtype = ctype.split('/', 1)     
        if maintype == 'text':
            msg = MIMEText(bodytext)
            print 'we got a problem here'
        # Set the filename parameter
        filestart,extension = fileName.split('.',1)
        fileName = filestart+'.dat'
        msg.add_header('Content-Disposition', 'attachment',

    # Now send the message

    s = smtplib.SMTP('smtp.paradise.net.nz')
    print 'connecting'
    s.sendmail(fromAddr, toAddr, outer.as_string())
    print 'sent email'

sender = email at address
copieraddr = email at address

send_dat_files('SU', '65AN88888',sender,copieraddr)


questions are:

1.  you may note that i have to change the file extension to .dat,
this is a requirement of the receiving device,  when i do that to the
file attachment directly,  the encoding does not work.  any idea why?

2.  the attachment files will be generated by anothe bit of code that
i am writing, it strikes me as being a bit clunky to wirte these to an
extenal folder then copy then in to the above,  is there anywhay that
i can take a string,  then pretend that it is a file and attach it to
the email?

sorry if this is a bit long.

look forward to hearing from anyone

kind regards

bill ramsay.

More information about the Python-list mailing list