Browse Source

Refactor email sending functions to allow customization

For example, if we need to use a custom From: address,
we can now do:

    m = make_message("template-name", recipient, ctx)
    m.from_email = "...."  # customize here
    send(m)
pull/551/head
Pēteris Caune 3 years ago
parent
commit
f3af13654e
No known key found for this signature in database GPG Key ID: E28D7679E9A9EDE2
1 changed files with 18 additions and 14 deletions
  1. +18
    -14
      hc/lib/emails.py

+ 18
- 14
hc/lib/emails.py View File

@ -20,7 +20,7 @@ class EmailThread(Thread):
# Make sure each retry creates a new connection:
self.message.connection = None
self.message.send()
# No exception--great, return from the retry loop
# No exception--great! Return from the retry loop
return
except smtplib.SMTPServerDisconnected as e:
if attempt + 1 == self.MAX_TRIES:
@ -32,7 +32,7 @@ class EmailThread(Thread):
time.sleep(1)
def send(name, to, ctx, headers={}, from_email=None):
def make_message(name, to, ctx, headers={}):
ctx["SITE_ROOT"] = settings.SITE_ROOT
subject = render("emails/%s-subject.html" % name, ctx).strip()
@ -41,11 +41,13 @@ def send(name, to, ctx, headers={}, from_email=None):
msg = EmailMultiAlternatives(subject, body, to=(to,), headers=headers)
msg.attach_alternative(html, "text/html")
if from_email:
msg.from_email = from_email
return msg
def send(msg, block=False):
t = EmailThread(msg)
if hasattr(settings, "BLOCKING_EMAILS"):
if block or hasattr(settings, "BLOCKING_EMAILS"):
# In tests, we send emails synchronously
# so we can inspect the outgoing messages
t.run()
@ -56,36 +58,38 @@ def send(name, to, ctx, headers={}, from_email=None):
def login(to, ctx):
send("login", to, ctx)
send(make_message("login", to, ctx))
def transfer_request(to, ctx):
send("transfer-request", to, ctx)
send(make_message("transfer-request", to, ctx))
def alert(to, ctx, headers={}):
send("alert", to, ctx, headers=headers)
send(make_message("alert", to, ctx, headers=headers))
def verify_email(to, ctx):
send("verify-email", to, ctx)
send(make_message("verify-email", to, ctx))
def report(to, ctx, headers={}):
send("report", to, ctx, headers=headers)
m = make_message("report", to, ctx, headers=headers)
send(m, block=True)
def deletion_notice(to, ctx, headers={}):
send("deletion-notice", to, ctx, headers=headers)
m = make_message("deletion-notice", to, ctx, headers=headers)
send(m, block=True)
def sms_limit(to, ctx):
send("sms-limit", to, ctx)
send(make_message("sms-limit", to, ctx))
def call_limit(to, ctx):
send("phone-call-limit", to, ctx)
send(make_message("phone-call-limit", to, ctx))
def sudo_code(to, ctx):
send("sudo-code", to, ctx)
send(make_message("sudo-code", to, ctx))

Loading…
Cancel
Save