Coverage for src/couchers/email/smtp.py: 35%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

23 statements  

1import email.utils 

2import smtplib 

3from email.mime.multipart import MIMEMultipart 

4from email.mime.text import MIMEText 

5 

6from couchers.config import config 

7from couchers.crypto import random_hex 

8from couchers.models import Email 

9 

10 

11def send_smtp_email(sender_name, sender_email, recipient, subject, plain, html): 

12 """ 

13 Sends out the email through SMTP, settings from config. 

14 

15 Returns a models.Email object that can be straight away added to the database. 

16 """ 

17 message_id = random_hex() 

18 msg = MIMEMultipart("alternative") 

19 msg["Subject"] = subject 

20 msg["From"] = email.utils.formataddr((sender_name, sender_email)) 

21 msg["To"] = recipient 

22 msg["X-Couchers-ID"] = message_id 

23 

24 msg.attach(MIMEText(plain, "plain")) 

25 msg.attach(MIMEText(html, "html")) 

26 

27 with smtplib.SMTP(config["SMTP_HOST"], config["SMTP_PORT"]) as server: 

28 server.ehlo() 

29 server.starttls() 

30 # stmplib docs recommend calling ehlo() before and after starttls() 

31 server.ehlo() 

32 server.login(config["SMTP_USERNAME"], config["SMTP_PASSWORD"]) 

33 server.sendmail(sender_email, recipient, msg.as_string()) 

34 

35 return Email( 

36 id=message_id, 

37 sender_name=sender_name, 

38 sender_email=sender_email, 

39 recipient=recipient, 

40 subject=subject, 

41 plain=plain, 

42 html=html, 

43 )