0

im adapating a script as per Sending Multipart html emails which contain embedded images and when Ive come to sending the mail, it fails but im not getting any return codes as to why it may have failed just a blank code. im using an internal mxrelay setup by our sysadmins.

#!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "infternal.settings")
import django
django.setup()
from django.conf import settings
import dateutil.parser
import re
import requests
import json
from O365 import *
from sites.models import SiteData
from sites.models import Circuits, CircuitMaintenance
from home.models import MailTemplate, MailImages
from jinja2 import Template, Environment
from django.db.models import Q
from datetime import datetime, timedelta
from django.conf import settings
from StringIO import StringIO
import smtplib    
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage

env = Environment(autoescape=False, optimized=False)       
template_data = MailTemplate.objects.get(pk=1)
mail_template = env.from_string(template_data.template)

template_file = StringIO()
mail_template.stream(
    StartDate   = '17/02/17 Midnight',
    EndDate     = '17/02/17 6 AM',
    Details     = 'Circuit maintenace on the cirasodasd asdas da a dskdka aks ada',   
).dump(template_file)

content = template_file.getvalue()

# Define these once; use them twice!
strFrom = 'helpdesk@xxxxx.com'
strTo = 'alex@xxxx.com'

# Create the root message and fill in the from, to, and subject headers
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = 'test message'
msgRoot['From'] = strFrom
msgRoot['To'] = strTo
msgRoot.preamble = 'This is a multi-part message in MIME format.'

# Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgText = MIMEText('This is the alternative plain text message.')
msgAlternative.attach(msgText)

# We reference the image in the IMG SRC attribute by the ID we give it below
msgText = MIMEText(content, 'html')
msgAlternative.attach(msgText)

mail_images = MailImages.objects.filter(mail_template=template_data)

count = 1
for i in mail_images:
    fp = open('{0}{1}'.format(settings.MEDIA_ROOT,i.image), 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
    msgImage.add_header('Content-ID', 'image_{0}'.format(count))
    msgRoot.attach(msgImage)
    count += 1

# Send the email (this example assumes SMTP authentication is required)
smtp = smtplib.SMTP()
smtp.connect('mxrelay.xxxx.com')
smtp.sendmail(strFrom, strTo, msgRoot.as_string())
smtp.quit()

output of sending below:

>>> smtp.connect('mxrelay.xxxxx.com')
(220, 'mxrelay-02.xxxxx.com ESMTP Postfix')
>>> smtp.sendmail(strFrom, strTo, msgRoot.as_string())
{}
>>>

I thought it might be the embedded images failing so i took that bit out and still got nothing back. does anyone know why i would not be returned a response code?

Thanks

*EDIT:

if i send smtp.sendmail(strFrom, strTo, 'TEST') i get the email, but sending msgRoot.as_string() fails, in either response though the code is {} but it works so it must be something to do with the msg, and comparing the code posted by Aidan i cant see any differences that would cause it to fail

Community
  • 1
  • 1
AlexW
  • 2,843
  • 12
  • 74
  • 156

1 Answers1

1

Here is a possible solution. pretty much taken straight from python 2.7 documentation.

        """
https://docs.python.org/2.7/library/email-examples.html
"""
from __future__ import print_function
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTPException

import smtplib
import datetime


COMMASPACE = ', '


def send_email(username, password, host, port, frmaddr, toaddrs, subj, 
               img_file, html):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subj
    msg['From'] = frmaddr
    msg['To'] = COMMASPACE.join(toaddrs)



    # Open the files in binary mode.  Let the MIMEImage class automatically
    # guess the specific image type.
    with open(img_file, 'rb') as fb:
        img = MIMEImage(fp.read())
        msg.attach(img)

    # attach some html alongside your image.
    msg.attach(MIMEText(html, 'html'))

    try:
        server = smtplib.SMTP(host, port)
        server.ehlo()
        server.starttls()
        server.login(username, password)
        server.sendmail(frmaddr, toaddrs, msg.as_string())
        server.close()

        log_msg = "email sent from {} to {} at {}" \
                  "".format(frmaddr, ", ".join(toaddrs),
                            datetime.datetime.utcnow())
        print(log_msg)
    except SMTPException as e:
        print(e)

"""
main function
"""
if __name__ == '__main__':
    username = input('Enter your email address: ')      # my_email@gmail.com
    password = input('Enter your password: ')
    host = input('Enter your host: ')   # smtp.gmail.com
    port = input('Enter your port: ')   # 587
    frmaddr = input('Enter the 'from' address: ')
    toaddrs = input('Enter the 'to' addresses (comma delimiter strings): ')
    subj = input('Enter your email subject: ')
    img_file = input('Enter your image file: ')


    send_email(username, password, host, port, frmaddr, toaddrs, subj=subj,
               img_file, html)
aidanmelen
  • 6,194
  • 1
  • 23
  • 24