Coverage for api/email.py: 20%

# Coverage for api/email.py : 20%

## 24 statements

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1"""

2 This file email.py contains functions for sending

3 text and html rendered emails asynchronously

4"""

5 from threading import Thread

6

7 from flask import current_app

8 from flask import render_template

9 from flask_mailman import EmailMultiAlternatives

10

11

12 def _send_email_helper(app, msg):

13 """

14 Helper function used for sending email message

15

16 Args:

17 app (Flask): The flask app object

18 msg (flask-mailman email object): any email/messsage object

19 defined for flask-mailman. Example EmailMessage

20 """

21 with app.app_context():

22 if (

23 "MAIL_USERNAME" not in current_app.config

24 or "MAIL_PASSWORD" not in current_app.config

25 or current_app.config["MAIL_USERNAME"] is None

26 or current_app.config["MAIL_PASSWORD"] is None

27 ):

28 print(

29 "\nShopyo Error: MAIL_USERNAME, and/or MAIL_PASSWORD not configured\n"

30 )

31 return

32

33 msg.send()

34

35

36 def send_async_email(to, subject, template, from_email=None, **kwargs):

37 """

38 Sends email anachronously i.e the function is non blocking.

39 Assume email template is valid i.e it can be rendered using

40 flask' render_template function and both .html and .txt

41 email template files exits

42

43 Args:

44 to (String): recipient of the email

45 subject (String): subject of the email

46 template (String): template file path to be used in email body

47 from_email (String, optional): sender of the email. If not set

48 MAIL_DEFAULT_SENDER is used from config.

49 """

50

51 if from_email is None:

52 if (

53 "MAIL_DEFAULT_SENDER" not in current_app.config

54 or current_app.config["MAIL_DEFAULT_SENDER"] is None

55 ):

56 print("\nShopyo Error: MAIL_DEFAULT_SENDER not configured\n")

57 return

58

59 from_email = current_app.config["MAIL_DEFAULT_SENDER"]

60

61 app = current_app._get_current_object()

62 template_txt = render_template(f"{template}.txt", **kwargs)

63 template_html = render_template(f"{template}.html", **kwargs)

64

65 msg = EmailMultiAlternatives(

66 subject=subject,

67 body=template_txt,

68 from_email=from_email,

69 to=[to],

70 )

71 msg.attach_alternative(template_html, "text/html")

72

73 thr = Thread(target=_send_email_helper, args=[app, msg])

74 thr.start()

75 return thr