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 smtplib import SMTPRecipientsRefused
20 from forum import settings
21 from django.template import loader, Context, Template
22 from forum.utils.html import sanitize_html
23 from forum.context import application_settings
24 from forum.utils.html2text import HTML2Text
25 from threading import Thread
27 def send_template_email(recipients, template, context):
28 t = loader.get_template(template)
29 context.update(dict(recipients=recipients, settings=settings))
30 t.render(Context(context))
32 def create_connection():
33 connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT),
34 local_hostname=DNS_NAME.get_fqdn())
36 if bool(settings.EMAIL_USE_TLS):
41 if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
42 connection.login(str(settings.EMAIL_HOST_USER), str(settings.EMAIL_HOST_PASSWORD))
47 def create_and_send_mail_messages(messages):
48 if not settings.EMAIL_HOST:
51 sender = Header(unicode(settings.APP_SHORT_NAME), 'utf-8')
52 sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL))
53 sender = u'%s <%s>' % (unicode(settings.APP_SHORT_NAME), unicode(settings.DEFAULT_FROM_EMAIL))
55 reply_to = unicode(settings.DEFAULT_REPLY_TO_EMAIL)
61 sender = str(settings.DEFAULT_FROM_EMAIL)
63 for recipient, subject, html, text, media in messages:
64 if connection is None:
65 connection = create_connection()
67 msgRoot = MIMEMultipart('related')
69 msgRoot['Subject'] = Header(subject, 'utf-8')
70 msgRoot['From'] = sender
72 to = Header(recipient.username, 'utf-8')
73 to.append('<%s>' % recipient.email)
77 msgRoot['Reply-To'] = reply_to
79 msgRoot.preamble = 'This is a multi-part message from %s.' % unicode(settings.APP_SHORT_NAME).encode('utf8')
81 msgAlternative = MIMEMultipart('alternative')
82 msgRoot.attach(msgAlternative)
84 msgAlternative.attach(MIMEText(text.encode('utf-8'), _charset='utf-8'))
85 msgAlternative.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8'))
87 for alias, location in media.items():
88 fp = open(location, 'rb')
89 msgImage = MIMEImage(fp.read())
91 msgImage.add_header('Content-ID', '<'+alias+'>')
92 msgRoot.attach(msgImage)
95 connection.sendmail(sender, [recipient.email], msgRoot.as_string())
96 except SMTPRecipientsRefused, e:
97 logging.error("Email address not accepted. Exception: %s" % e)
99 logging.error("Couldn't send mail using the sendmail method: %s" % e)
109 except AttributeError:
111 except socket.sslerror:
114 logging.error('Email sending has failed: %s' % e)