Python sendmail with text file content
Question: I want to send mail via python script, I need it to alert me about some missed
files.

scripy have to read log file(*.txt) and send content of this file into my
mail, so I made it:

    
    
    import smtplib, os
    from email.mime.text import MIMEText
    
    
    raport_file = open('alert.txt','rb')
    alert_msg = MIMEText(raport_file.read().encode("utf-8"), 'plain', 'utf-8')
    raport_file.close()
    
    
    
    
    m = smtplib.SMTP()
    m.connect("*****", 25)
    m.sendmail("Check_Files", "*****", alert_msg.as_string())
    m.quit()
    

script run, but there is no mail at all. If I replace alert_msg.as_string()
with "any text", everything works fine.


Answer: 
    import smtplib
    import base64
    import os
    import sys
    
    FROM = 'user@user.com'
    TO = 'user@user.com'
    MARKER = 'SIMPLE_MARKER_GOES_HERE'
    
    if __name__ == "__main__":
        filename = 'name_of_file'
    
        # Read a file and encode it into base64 format
        fo = open(filename, "rb")
        filecontent = fo.read()
        encodedcontent = base64.b64encode(filecontent)  # base64
        filename = os.path.basename(filename)
    
        body ="""
    Insert whatever message you want here or dynamically create.
    """
    
        # Define the main headers.
        part1 = """From: Matt Vincent <matt.vincent@jax.org>
    To: %s
    Subject: Sending Attachment
    MIME-Version: 1.0
    Content-Type: multipart/mixed; boundary=%s
    --%s
    """ % (TO, MARKER, MARKER)
    
        # Define the message action
        part2 = """Content-Type: text/plain
    Content-Transfer-Encoding:8bit
    
    %s
    --%s
    """ % (body, MARKER)
    
        # Define the attachment section
        part3 = """Content-Type: multipart/mixed; name=\"%s\"
    Content-Transfer-Encoding:base64
    Content-Disposition: attachment; filename=%s
    
    %s
    --%s--
    """ %(filename, filename, encodedcontent, MARKER)
    
        message = part1 + part2 + part3
    
        try:
            smtpObj = smtplib.SMTP('domainhere')
            smtpObj.sendmail(FROM, TO, message)
            print "Successfully sent email"
        except Exception:
            print "Error: unable to send email"
    

