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, видит любые различия, которые могут привести к его сбою.
Вы отправили здесь два набора кода. С кем вы хотите помочь? – e4c5
Я не думаю, что у меня есть, это одна часть кода для отправки электронной почты, возможно, второй импорт бросил вас? ive переместил его вверх. Спасибо – AlexW
Что дает 'print (msgRoot.as_string())'? –