Python SMTP/MIME Message body

5.2k views Asked by At

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 = '[email protected]'  # raw_input("Sender: ")
receiver = '[email protected]'  # 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 <[email protected]>
To: To Person <[email protected]>
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.

2

There are 2 answers

0
Googlesomething On BEST ANSWER

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."
1
notorious.no On

You shouldn't be reinventing the wheel. Use the mime modules Python has included in the standard library instead of trying to create the headers on your own. I haven't been able to test it out but check if this works:

import smtplib
import base64
import ConfigParser
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

filename = "test.pcapng"

with open(filename, 'rb') as fo:
    filecontent = fo.read()
    encoded_content = base64.b64encode(filecontent)

sender = '[email protected]'  # raw_input("Sender: ")
receiver = '[email protected]'  # 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.
"""

message = MIMEMultipart(
    From=sender,
    To=receiver,
    Subject='Sending Attachment')

message.attach(MIMEText(body))          # body of the email

message.attach(MIMEApplication(
    encoded_content,
    Content_Disposition='attachment; filename="{0}"'.format(filename))  # b64 encoded file
    )

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

I've left off a few parts (like the ConfigParser variables) and demonstrated only the email related portions.

References:

How to send email attachments with Python