Hide keyboard shortcuts

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""" 

2This file email.py contains functions for sending 

3text and html rendered emails asynchronously 

4""" 

5from threading import Thread 

6 

7from flask import current_app 

8from flask import render_template 

9from flask_mailman import EmailMultiAlternatives 

10 

11 

12def _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 

36def 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