1
0
mirror of https://github.com/laurivosandi/certidude synced 2024-12-22 08:15:18 +00:00

mailer: Better utf-8 handling

This commit is contained in:
Lauri Võsandi 2018-05-16 13:10:26 +00:00
parent adff4a0a50
commit c6d117b9cf
2 changed files with 21 additions and 8 deletions

View File

@ -8,6 +8,7 @@ from jinja2 import Environment, PackageLoader
from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText from email.mime.text import MIMEText
from email.mime.base import MIMEBase from email.mime.base import MIMEBase
from email.header import Header
from urllib.parse import urlparse from urllib.parse import urlparse
env = Environment(loader=PackageLoader("certidude", "templates/mail")) env = Environment(loader=PackageLoader("certidude", "templates/mail"))
@ -30,9 +31,18 @@ def send(template, to=None, secondary=None, include_admins=True, attachments=(),
html = markdown(text) html = markdown(text)
msg = MIMEMultipart("alternative") msg = MIMEMultipart("alternative")
msg["Subject"] = subject msg["Subject"] = Header(subject)
msg["From"] = "%s <%s>" % (config.MAILER_NAME, config.MAILER_ADDRESS) msg["From"] = Header(config.MAILER_NAME)
msg["To"] = ", ".join([str(j) for j in recipients]) msg["From"].append("<%s>" % config.MAILER_ADDRESS)
msg["To"] = Header()
for user in recipients:
if isinstance(user, User):
full_name, user = user.format()
if full_name:
msg["To"].append(full_name)
msg["To"].append(user)
msg["To"].append(", ")
part1 = MIMEText(text, "plain", "utf-8") part1 = MIMEText(text, "plain", "utf-8")
part2 = MIMEText(html, "html", "utf-8") part2 = MIMEText(html, "html", "utf-8")
@ -49,4 +59,4 @@ def send(template, to=None, secondary=None, include_admins=True, attachments=(),
if config.MAILER_ADDRESS: if config.MAILER_ADDRESS:
click.echo("Sending to: %s" % msg["to"]) click.echo("Sending to: %s" % msg["to"])
conn = smtplib.SMTP("localhost") conn = smtplib.SMTP("localhost")
conn.sendmail(config.MAILER_ADDRESS, [str(u) for u in recipients], msg.as_string()) conn.sendmail(config.MAILER_ADDRESS, [u.mail if isinstance(u, User) else u for u in recipients], msg.as_string())

View File

@ -12,11 +12,14 @@ class User(object):
self.given_name = given_name self.given_name = given_name
self.surname = surname self.surname = surname
def __repr__(self): def format(self):
if self.given_name and self.surname: if self.given_name or self.surname:
return "%s %s <%s>" % (self.given_name, self.surname, self.mail) return " ".join([j for j in [self.given_name, self.surname] if j]), "<%s>" % self.mail
else: else:
return self.mail return None, self.mail
def __repr__(self):
return " ".join([j for j in self.format() if j])
def __hash__(self): def __hash__(self):
return hash(self.mail) return hash(self.mail)