Buckler/mail.py
2019-09-19 20:49:40 -04:00

57 lines
1.5 KiB
Python

#!/usr/bin/env python3
"""
Tools for sending emails.
"""
import email.mime.text
import smtplib
import secrets
import config
def send_mail(to_addr, subject, body):
"""
Sends an email.
"""
msg = email.mime.text.MIMEText(body, 'plain', 'utf8')
msg['From'] = config.email['user']
msg['To'] = to_addr
msg['Subject'] = subject
with smtplib.SMTP_SSL(config.email['host'],config.email['port']) as server:
server.login(config.email['user'], config.email['password'])
server.send_message(msg)
async def send_invite(request, to_addr):
"""
Sends an invitation.
"""
token = secrets.token_urlsafe(32)
async with request.app['pool'].acquire() as conn:
await conn.execute(
"INSERT INTO invite (email, token) "
"VALUES ($1, $2)",
to_addr, token)
d = {'invite': token}
invite_url = request.app.router['register'].url_for().with_query(d)
invite_url = config.server_domain + config.url_prefix + invite_url
body = "Buckle up.\n" + invite_url
send_mail(to_addr, "Buckler Invite", body)
async def send_confirmation(request, user_id, to_addr):
"""
Sends an email confirmation.
"""
token = secrets.token_urlsafe(32)
async with request.app['pool'].acquire() as conn:
await conn.execute(
"INSERT INTO email_confirmation (user_id, token) "
"VALUES ($1, $2)",
user_id, token)
d = {'confirm': token}
confirm_url = request.app.router['register'].url_for().with_query(d)
confirm_url = config.server_domain + str(confirm_url)
body = "Buckle up.\n" + confirm_url
send_mail(to_addr, "Buckler Invite", body)