source: OpenWorkouts-current/ow/mail.py @ b8ef4ab

currentfeature/docs
Last change on this file since b8ef4ab was b8ef4ab, checked in by Borja Lopez <borja@…>, 5 years ago

(#61) Better templates for "verify your account" emails:

  • Send a multipart text/html email (instead text only)
  • Added some styling to the html version of the email, based on our current login page styles.

Important: as the html version contains html code generated using
request.resource_url() and request.static_url(), when running in
development mode under http://localhost, the links to images
and css files in the rendered email point to localhost, so they
won't work outside the machine running openworkouts.

  • Property mode set to 100644
File size: 1.9 KB
Line 
1import logging
2
3from pyramid_mailer import get_mailer
4from pyramid_mailer.message import Message
5from pyramid.renderers import render
6from pyramid.i18n import TranslationStringFactory
7
8_ = TranslationStringFactory('OpenWorkouts')
9
10log = logging.getLogger(__name__)
11
12
13def idna_encode_recipients(message):
14    """
15    Given a pyramid_mailer.message.Message instance, check if the recipient(s)
16    domain name(s) contain non-ascii characters and, if so, encode the domain
17    name part of the address(es) properly
18
19    >>> from pyramid_mailer.message import Message
20    >>> message = Message(subject='s', recipients=['a@a.com'], body='b')
21    >>> assert message.recipients == ['a@a.com']
22    >>> message = idna_encode_recipients(message)
23    >>> assert message.recipients == ['a@a.com']
24    >>> message.recipients.append(u'a@\xfc.de')
25    >>> assert message.recipients == ['a@a.com', u'a@\xfc.de']
26    >>> message = idna_encode_recipients(message)
27    >>> message.recipients
28    ['a@a.com', 'a@xn--tda.de']
29    """
30    recipients = []
31    for rcpt in message.recipients:
32        username, domain = rcpt.split('@')
33        recipients.append(
34            '@'.join([username, domain.encode('idna').decode('utf-8')]))
35    message.recipients = recipients
36    return message
37
38
39def send_verification_email(request, user):
40    subject = _('Welcome to OpenWorkouts')
41    txt_template = 'ow:templates/mail_verify_account_txt.pt'
42    html_template = 'ow:templates/mail_verify_account_html.pt'
43    verify_link = request.resource_url(user, 'verify', user.verification_token)
44    context = {'user': user, 'verify_link': verify_link}
45    mailer = get_mailer(request)
46    txt_body = render(txt_template, context, request)
47    html_body = render(html_template, context, request)
48    message = Message(
49        subject=subject,
50        recipients=[user.email],
51        body=txt_body,
52        html=html_body
53    )
54    message = idna_encode_recipients(message)
55    mailer.send_to_queue(message)
Note: See TracBrowser for help on using the repository browser.