Search code examples
pythonpython-2.7smtpmimesmtplib

Python SMTP/MIME Message body


I've been working on this for 2 days now and managed to get this script with a pcapng file attached to send but I cannot seem to make the message body appear in the email.

import smtplib
import base64
import ConfigParser
#from email.MIMEapplication import MIMEApplication
#from email.MIMEmultipart import MIMEMultipart
#from email.MIMEtext import MIMEText
#from email.utils import COMMASPACE, formatdate

Config = ConfigParser.ConfigParser()
Config.read('mailsend.ini')

filename = "test.pcapng"

fo = open(filename, "rb")
filecontent = fo.read()
encoded_content = base64.b64encode(filecontent)  # base 64

sender = 'notareal@email.com'  # raw_input("Sender: ")
receiver = 'someother@fakeemail.com'  # raw_input("Recipient: ")

marker = raw_input("Please input a unique set of numbers that will not be found elsewhere in the message, ie- roll face: ")

body ="""
This is a test email to send an attachment.
"""

# Define the main headers
header = """ From: From Person <notareal@email.com>
To: To Person <someother@fakeemail.com>
Subject: Sending Attachment
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)

# Define message action
message_action = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body, marker)

# Define the attachment section
message_attachment = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s
--%s--
""" % (filename, filename, encoded_content, marker)

message = header + message_action + message_attachment

try:
    smtpObj = smtplib.SMTP('smtp.gmail.com')
    smtpObj.sendmail(sender, receiver, message)
    print "Successfully sent email!"
except Exception:
    print "Error: unable to send email"

My goal is to ultimately have this script send an email after reading the parameters from a config file and attach a pcapng file along with some other text data describing the wireshark event. The email is not showing the body of the message when sent. The pcapng file is just a test file full of fake ips and subnets for now. Where have I gone wrong with the message body?

def mail_man():
    if ms == 'Y' or ms == 'y' and ms_maxattach <= int(smtp.esmtp_features['size']):
        fromaddr = [ms_from]
        toaddr = [ms_sendto]
        cc = [ms_cc]
        bcc = [ms_bcc]

        msg = MIMEMultipart()

        body = "\nYou're captured event is attached. \nThis is an automated email generated by Dumpcap.py"

        msg.attach("From: %s\r\n" % fromaddr
        + "To: %s\r\n" % toaddr
        + "CC: %s\r\n" % ",".join(cc)
        + "Subject: %s\r\n" % ms_subject
        + "X-Priority = %s\r\n" % ms_importance
        + "\r\n"
        + "%s\r\n" % body
        + "%s\r\n" % ms_pm)
        toaddrs = [toaddr] + cc + bcc

        msg.attach(MIMEText(body, 'plain'))

        filename = "dcdflts.cong"
        attachment = open(filename, "rb")

        if ms_attach == 'y' or ms_attach == "Y":
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(attachment.read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
            msg.attach(part)

        server = smtplib.SMTP(ms_smtp_server[ms_smtp_port])
        server.starttls()
        server.login(fromaddr, "YOURPASSWORD")
        text = msg.as_string()
        server.sendmail(fromaddr, toaddrs, text)
        server.quit()

This is my second attempt, all "ms_..." variables are global through a larger program.


Solution

  • Figured it out, with added ConfigParser. This is fully functional with a .ini file

    import smtplib
    ####import sys#### duplicate
    from email.parser import Parser
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.base import MIMEBase
    from email import encoders
    import ConfigParser
    
    
    def mail_man(cfg_file, event_file):
        # Parse email configs from cfg file
        Config = ConfigParser.ConfigParser()
        Config.read(str(cfg_file))
    
        mail_man_start = Config.get('DC_MS', 'ms')
        security = Config.get('DC_MS', 'ms_security')
        add_attachment = Config.get('DC_MS', 'ms_attach')
        try:
            if mail_man_start == "y" or mail_man_start == "Y":
                fromaddr = Config.get("DC_MS", "ms_from")
                addresses = [Config.get("DC_MS", "ms_sendto")] + [Config.get("DC_MS", "ms_cc")] + [Config.get("DC_MS", "ms_bcc")]
    
                msg = MIMEMultipart()  # creates multipart email
                msg['Subject'] = Config.get('DC_MS', 'ms_subject')  # sets up the header
                msg['From'] = Config.get('DC_MS', 'ms_from')
                msg['To'] = Config.get('DC_MS', 'ms_sendto')
                msg['reply-to'] = Config.get('DC_MS', 'ms_replyto')
                msg['X-Priority'] = Config.get('DC_MS', 'ms_importance')
                msg['CC'] = Config.get('DC_MS', 'ms_cc')
                msg['BCC'] = Config.get('DC_MS', 'ms_bcc')
                msg['Return-Receipt-To'] = Config.get('DC_MS', 'ms_rrr')
                msg.preamble = 'Event Notification'
    
                message = '... use this to add a body to the email detailing event. dumpcap.py location??'
                msg.attach(MIMEText(message))   # attaches body to email
    
                # Adds attachment if ms_attach = Y/y
                if add_attachment == "y" or add_attachment == "Y":
                    attachment = open(event_file, "rb")
                    # Encodes the attachment and adds it to the email
                    part = MIMEBase('application', 'octet-stream')
                    part.set_payload(attachment.read())
                    encoders.encode_base64(part)
                    part.add_header('Content-Disposition', "attachment; filename = %s" % event_file)
    
                    msg.attach(part)
                else:
                    print "No attachment sent."
    
                server = smtplib.SMTP(Config.get('DC_MS', 'ms_smtp_server'), Config.get('DC_MS', 'ms_smtp_port'))
                server.ehlo()
                server.starttls()
                if security == "y" or security == "Y":
                    server.login(Config.get('DC_MS', 'ms_user'), Config.get('DC_MS', 'ms_password'))
                text = msg.as_string()
                max_size = Config.get('DC_MS', 'ms_maxattach')
                msg_size = sys.getsizeof(msg)
                if msg_size <= max_size:
                    server.sendmail(fromaddr, addresses, text)
                else:
                    print "Your message exceeds maximum attachment size.\n Please Try again"
                server.quit()
                attachment.close()
            else:
                print "Mail_man not activated"
        except:
           print "Error! Something went wrong with Mail Man. Please try again."