2017-02-20 10 views
0

im, адаптировав скрипт согласно Sending Multipart html emails which contain embedded images, и когда Ive придет к отправке почты, он не сработает, но я не получаю никаких кодов возврата, почему он, возможно, код. im используя внутреннюю настройку mxrelay нашими системными администраторами.python smtplib - отправить почту не удалось с помощью msgRoot.as_string()

#!/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 = '[email protected]' 
strTo = '[email protected]' 

# 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() 

выход отправки ниже:

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

Я думал, что это может быть встроенными изображениями неудовлетворительных, так что я взял, что немного, и до сих пор ничего не получил обратно. Кто-нибудь знает, почему я не вернул бы код ответа?

Благодаря

* EDIT:

если я отправить smtp.sendmail (strFrom, strTo, 'TEST') я получаю электронную почту, но отсылка msgRoot.as_string() терпит неудачу, либо ответ, хотя код {}, но он работает так, что это должно быть связано с сообщением msg, и сравнение кода, опубликованного Aidan i can not, видит любые различия, которые могут привести к его сбою.

+0

Вы отправили здесь два набора кода. С кем вы хотите помочь? – e4c5

+0

Я не думаю, что у меня есть, это одна часть кода для отправки электронной почты, возможно, второй импорт бросил вас? ive переместил его вверх. Спасибо – AlexW

+0

Что дает 'print (msgRoot.as_string())'? –

ответ

1

Вот возможное решение. в значительной степени взяты из документации python 2.7.

 """ 
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: ')  # [email protected] 
    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)