]> git.openstreetmap.org Git - osqa.git/blob - forum/utils/mail.py
Merge pull request #26 from udacity/remove_dj_version
[osqa.git] / forum / utils / mail.py
1 import email
2 import socket
3 import os
4 import logging
5
6 try:
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
11 except:
12     from email.MIMEMultipart import MIMEMultipart
13     from email.MIMEText import MIMEText
14     from email.MIMEImage import MIMEImage
15     from email.Header import Header
16
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
26
27 def send_template_email(recipients, template, context, sender=None, reply_to = None):
28     t = loader.get_template(template)
29     context.update(dict(recipients=recipients, settings=settings, sender=sender, reply_to=reply_to))
30     t.render(Context(context))
31
32 def create_connection():
33     connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT),
34                           local_hostname=DNS_NAME.get_fqdn())
35
36     if bool(settings.EMAIL_USE_TLS):
37         connection.ehlo()
38         connection.starttls()
39         connection.ehlo()
40
41     if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
42         connection.login(str(settings.EMAIL_HOST_USER), str(settings.EMAIL_HOST_PASSWORD))
43
44     return connection
45
46
47 def create_and_send_mail_messages(messages, sender_data=None, reply_to=None):
48     if not settings.EMAIL_HOST:
49         return
50
51     sender = Header(unicode(settings.APP_SHORT_NAME), 'utf-8')
52     
53     if sender_data == None:
54         sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL))
55         sender = u'%s <%s>' % (unicode(settings.APP_SHORT_NAME), unicode(settings.DEFAULT_FROM_EMAIL))
56     else:
57         sender.append('<%s>' % unicode(sender_data['email']))
58         sender = u'%s <%s>' % (unicode(sender_data['name']), unicode(sender_data['email']))
59         
60     
61     if reply_to == None:
62         reply_to = unicode(settings.DEFAULT_REPLY_TO_EMAIL)
63     else:
64         reply_to = unicode(reply_to)
65
66     try:
67         connection = None
68
69         if sender is None:
70             sender = str(settings.DEFAULT_FROM_EMAIL)
71
72         for recipient, subject, html, text, media in messages:
73             if connection is None:
74                 connection = create_connection()
75
76             msgRoot = MIMEMultipart('related')
77
78             msgRoot['Subject'] = Header(subject, 'utf-8')
79             msgRoot['From'] = sender
80
81             to = Header(u"%s <%s>" % (recipient.username, recipient.email), 'utf-8')
82             msgRoot['To'] = to
83
84             if reply_to:
85                 msgRoot['Reply-To'] = reply_to
86
87             msgRoot.preamble = 'This is a multi-part message from %s.' % unicode(settings.APP_SHORT_NAME).encode('utf8')
88
89             msgAlternative = MIMEMultipart('alternative')
90             msgRoot.attach(msgAlternative)
91
92             msgAlternative.attach(MIMEText(text.encode('utf-8'), _charset='utf-8'))
93             msgAlternative.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8'))
94
95             for alias, location in media.items():
96                 fp = open(location, 'rb')
97                 msgImage = MIMEImage(fp.read())
98                 fp.close()
99                 msgImage.add_header('Content-ID', '<'+alias+'>')
100                 msgRoot.attach(msgImage)
101
102             try:
103                 connection.sendmail(sender, [recipient.email], msgRoot.as_string())
104             except SMTPRecipientsRefused, e:
105                 logging.error("Email address not accepted.  Exception: %s" % e)
106             except Exception, e:
107                 logging.error("Couldn't send mail using the sendmail method: %s" % e)
108                 try:
109                     connection.quit()
110                 except Exception, e:
111                     logging.error(e)
112                 finally:
113                     connection = None
114
115         try:
116             connection.quit()
117         except AttributeError:
118             pass
119         except socket.sslerror:
120             connection.close()
121     except Exception, e:
122         logging.error('Email sending has failed: %s' % e)