Search code examples
pythonstringvariablesemail-attachments

Sending an attachment in mail using a variable as data container python


I'd like to know if it was possible to send a variable (say a string) as an attachment in a mail using python. The goal is to avoid the making of temporary files in the process.

As an example, I'd like to send a string which is formatted as a csv as an attachment to a mail and possibly this attachment could later be downloaded as a file on the other end of the tunnel.

Thanks for all of your possible help.

EDIT: It now works with StringIO, thank you for your help. Answer below


Solution

  • So here's the working method that I am now using:

    #!/usr/bin/python2.7.x
    # -*- coding: utf-8 -*-  
    #Imports
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
    from email.MIMEBase import MIMEBase
    from email import encoders
    from email.Utils import COMMASPACE, formatdate
    import sys
    try:
        from StringIO import StringIO
    except:
        print("Could not import critical library StringIO")
        sys.exit(0)
    import smtplib
    import datetime
    
    def run_mail(self):
    
        date = datetime.datetime.now()
        dateAAAAMMDD = str(date.year) + "_" + str( date.month) + "_" +str( date.day)
    
    
        pj1 = StringIO(self.pj1_data)
        pj1_name = "my_att_name_" + str(dateAAAAMMDD) + ".csv"
    
        pj2 = StringIO(self.pj2_data)
        pj2_name = "my_att_name2_" + str(dateAAAAMMDD) + ".txt"
    
        pj3 = StringIO(self.pj3_data)
        pj3_name = "my_att_name3_" + str(dateAAAAMMDD) + ".txt"
    
        pj =[(pj1,pj1_name), (pj2,pj2_name), (pj3,pj3_name)]
    
        fromaddr = 'address@something.com'
        toaddr = 'toanotheraddress@something.com'
        msg = MIMEMultipart()
        subject = 'subject dated ' + dateAAAAMMDD
        msg['From'] = fromaddr
        msg['To'] = toaddr
        msg['Subject'] = subject 
    
        msg.attach(MIMEText("Auto-generated script", 'plain'))
    
        for data, att_name in pj :
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(data.read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename= "%s"' % att_name)
            msg.attach(part)
        server_port = 25
        server = smtplib.SMTP('myserver.com',server_port)
        server.starttls()
        #If login required, not very secure, use either input or localhost without
        #login required
        server.login(fromaddr, 'MyPasswordGoesHere') 
    
        content = msg.as_string()
        server.sendmail(fromaddr,toaddr,content)
    
    
        server.quit()