7 from email.mime.multipart import MIMEMultipart
8 from email.mime.text import MIMEText
9 from email.mime.image import MIMEImage
10 from email.header import Header
12 from email.MIMEMultipart import MIMEMultipart
13 from email.MIMEText import MIMEText
14 from email.MIMEImage import MIMEImage
15 from email.Header import Header
17 from django.core.mail import DNS_NAME
18 from smtplib import SMTP
19 from forum import settings
20 from django.template import loader, Context, Template
21 from forum.utils.html import sanitize_html
22 from forum.context import application_settings
23 from forum.utils.html2text import HTML2Text
24 from threading import Thread
26 def send_template_email(recipients, template, context):
27 t = loader.get_template(template)
28 context.update(dict(recipients=recipients, settings=settings))
29 t.render(Context(context))
31 def create_and_send_mail_messages(messages):
32 if not settings.EMAIL_HOST:
35 sender = Header(unicode(settings.APP_SHORT_NAME), 'utf-8')
36 sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL))
37 sender = u'%s <%s>' % (unicode(settings.APP_SHORT_NAME), unicode(settings.DEFAULT_FROM_EMAIL))
40 connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT),
41 local_hostname=DNS_NAME.get_fqdn())
43 if (bool(settings.EMAIL_USE_TLS)):
48 if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
49 connection.login(str(settings.EMAIL_HOST_USER), str(settings.EMAIL_HOST_PASSWORD))
52 sender = str(settings.DEFAULT_FROM_EMAIL)
54 for recipient, subject, html, text, media in messages:
55 msgRoot = MIMEMultipart('related')
57 msgRoot['Subject'] = Header(subject, 'utf-8')
58 msgRoot['From'] = sender
60 to = Header(recipient.username, 'utf-8')
61 to.append('<%s>' % recipient.email)
64 msgRoot.preamble = 'This is a multi-part message from %s.' % unicode(settings.APP_SHORT_NAME).encode('utf8')
66 msgAlternative = MIMEMultipart('alternative')
67 msgRoot.attach(msgAlternative)
69 msgAlternative.attach(MIMEText(text.encode('utf-8'), _charset='utf-8'))
70 msgAlternative.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8'))
72 for alias, location in media.items():
73 fp = open(location, 'rb')
74 msgImage = MIMEImage(fp.read())
76 msgImage.add_header('Content-ID', '<'+alias+'>')
77 msgRoot.attach(msgImage)
80 connection.sendmail(sender, [recipient.email], msgRoot.as_string())
82 logging.error("Couldn't send mail using the sendmail method: %s" % e)
86 except socket.sslerror:
89 logging.error('Email sending has failed: %s' % e)