-
Notifications
You must be signed in to change notification settings - Fork 2k
/
mailer.py
170 lines (144 loc) · 5.48 KB
/
mailer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import smtplib
import logging
import uuid
from time import time
from email.mime.text import MIMEText
from email.header import Header
from email import Utils
from pylons import config
import paste.deploy.converters
import ckan
import ckan.model as model
import ckan.lib.helpers as h
from ckan.common import _, g
log = logging.getLogger(__name__)
class MailerException(Exception):
pass
def add_msg_niceties(recipient_name, body, sender_name, sender_url):
return _(u"Dear %s,") % recipient_name \
+ u"\r\n\r\n%s\r\n\r\n" % body \
+ u"--\r\n%s (%s)" % (sender_name, sender_url)
def _mail_recipient(recipient_name, recipient_email,
sender_name, sender_url, subject,
body, headers={}):
mail_from = config.get('smtp.mail_from')
body = add_msg_niceties(recipient_name, body, sender_name, sender_url)
msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
for k, v in headers.items():
if k in msg.keys():
msg.replace_header(k, v)
else:
msg.add_header(k, v)
subject = Header(subject.encode('utf-8'), 'utf-8')
msg['Subject'] = subject
msg['From'] = _("%s <%s>") % (sender_name, mail_from)
recipient = u"%s <%s>" % (recipient_name, recipient_email)
msg['To'] = Header(recipient, 'utf-8')
msg['Date'] = Utils.formatdate(time())
msg['X-Mailer'] = "CKAN %s" % ckan.__version__
# Send the email using Python's smtplib.
smtp_connection = smtplib.SMTP()
if 'smtp.test_server' in config:
# If 'smtp.test_server' is configured we assume we're running tests,
# and don't use the smtp.server, starttls, user, password etc. options.
smtp_server = config['smtp.test_server']
smtp_starttls = False
smtp_user = None
smtp_password = None
else:
smtp_server = config.get('smtp.server', 'localhost')
smtp_starttls = paste.deploy.converters.asbool(
config.get('smtp.starttls'))
smtp_user = config.get('smtp.user')
smtp_password = config.get('smtp.password')
smtp_connection.connect(smtp_server)
try:
#smtp_connection.set_debuglevel(True)
# Identify ourselves and prompt the server for supported features.
smtp_connection.ehlo()
# If 'smtp.starttls' is on in CKAN config, try to put the SMTP
# connection into TLS mode.
if smtp_starttls:
if smtp_connection.has_extn('STARTTLS'):
smtp_connection.starttls()
# Re-identify ourselves over TLS connection.
smtp_connection.ehlo()
else:
raise MailerException("SMTP server does not support STARTTLS")
# If 'smtp.user' is in CKAN config, try to login to SMTP server.
if smtp_user:
assert smtp_password, ("If smtp.user is configured then "
"smtp.password must be configured as well.")
smtp_connection.login(smtp_user, smtp_password)
smtp_connection.sendmail(mail_from, [recipient_email], msg.as_string())
log.info("Sent email to {0}".format(recipient_email))
except smtplib.SMTPException, e:
msg = '%r' % e
log.exception(msg)
raise MailerException(msg)
finally:
smtp_connection.quit()
def mail_recipient(recipient_name, recipient_email, subject,
body, headers={}):
return _mail_recipient(recipient_name, recipient_email,
g.site_title, g.site_url, subject, body, headers=headers)
def mail_user(recipient, subject, body, headers={}):
if (recipient.email is None) or not len(recipient.email):
raise MailerException(_("No recipient email address available!"))
mail_recipient(recipient.display_name, recipient.email, subject,
body, headers=headers)
def get_reset_link_body(user):
reset_link_message = _(
"You have requested your password on {site_title} to be reset.\n"
"\n"
"Please click the following link to confirm this request:\n"
"\n"
" {reset_link}\n"
)
d = {
'reset_link': get_reset_link(user),
'site_title': g.site_title
}
return reset_link_message.format(**d)
def get_invite_body(user):
invite_message = _(
"You have been invited to {site_title}. A user has already been created "
"to you with the username {user_name}. You can change it later.\n"
"\n"
"To accept this invite, please reset your password at:\n"
"\n"
" {reset_link}\n"
)
d = {
'reset_link': get_reset_link(user),
'site_title': g.site_title,
'user_name': user.name,
}
return invite_message.format(**d)
def get_reset_link(user):
return h.url_for(controller='user',
action='perform_reset',
id=user.id,
key=user.reset_key,
qualified=True)
def send_reset_link(user):
create_reset_key(user)
body = get_reset_link_body(user)
subject = _('Reset your password')
mail_user(user, subject, body)
def send_invite(user):
create_reset_key(user)
body = get_invite_body(user)
subject = _('Invite for {site_title}').format(site_title=g.site_title)
mail_user(user, subject, body)
def create_reset_key(user):
user.reset_key = unicode(make_key())
model.repo.commit_and_remove()
def make_key():
return uuid.uuid4().hex[:10]
def verify_reset_link(user, key):
if not key:
return False
if not user.reset_key or len(user.reset_key) < 5:
return False
return key.strip() == user.reset_key