2017-02-20 8 views
0

Sending Multipart html emails which contain embedded imagesのようにスクリプトを適用してメールを送信すると失敗しますが、なぜそれが空白で失敗したのかコード。システム管理者が内部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によって投稿されたコードを比較すると失敗する可能性がある相違点を確認してください。

+0

ここには2組のコードが掲載されています。あなたは助けが必要なのはどちらですか? – e4c5

+0

私は持っているとは思わない、これは電子メールを送信するためのコードの一部です、おそらく2番目のインポートはあなたを投げた?それを上に移動した。ありがとう – 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) 
関連する問題