Coverage for portality/app_email.py: 34%

80 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 13:43 +0000

1# ~~Email:Library~~ 

2import logging 

3 

4from flask import render_template, flash 

5from flask_mail import Mail, Message, Attachment 

6from portality.core import app 

7 

8import uuid 

9import markdown 

10 

11 

12class EmailException(Exception): 

13 pass 

14 

15 

16def send_markdown_mail(to, fro, subject, template_name=None, bcc=None, files=None, msg_body=None, markdown_template_name=None, **template_params): 

17 html_body = None 

18 if markdown_template_name: 

19 try: 

20 markdown_body = render_template(markdown_template_name, **template_params) 

21 except: 

22 with app.test_request_context(): 

23 markdown_body = render_template(markdown_template_name, **template_params) 

24 

25 md = markdown.Markdown() 

26 html_body = md.convert(markdown_body) 

27 

28 send_mail(to, fro, subject, template_name=template_name, bcc=bcc, files=files, msg_body=msg_body, html_body=html_body, html_body_flag=True, **template_params) 

29 

30# Flask-Mail version of email service from util.py 

31def send_mail(to, fro, subject, template_name=None, plaintext_template_name=None, bcc=None, files=None, msg_body=None, html_body=None, html_body_flag=False, **template_params): 

32 """ 

33 ~~-> Email:ExternalService~~ 

34 ~~-> FlaskMail:Library~~ 

35 :param to: 

36 :param fro: 

37 :param subject: 

38 :param template_name: HTML template name (used for HTML body when html_body_flag is True and html_body not provided) 

39 :param plaintext_template_name: Plain text template name (used for the plain text body if provided) 

40 :param bcc: 

41 :param files: 

42 :param msg_body: 

43 :param html_body_flag: 

44 :param html_body: 

45 :param template_params: 

46 :return: 

47 """ 

48 bcc = [] if bcc is None else bcc 

49 files = [] if files is None else files 

50 

51 # ensure that email isn't sent if it is disabled 

52 if not app.config.get("ENABLE_EMAIL", False): 

53 app.logger.info("Email template {0} called to send, but email has been disabled.\nto:{1}\tsubject:{2}".format(template_name, to, subject)) 

54 return 

55 

56 assert type(to) == list 

57 assert type(files) == list 

58 if bcc and not isinstance(bcc, list): 

59 bcc = [bcc] 

60 

61 to_is_invalid = True 

62 for t in to: 

63 if t: 

64 to_is_invalid = False 

65 # a list of None, None, None or even just a [None] is no good! 

66 

67 if to_is_invalid: 

68 magic = str(uuid.uuid1()) 

69 app.logger.error('Bad To list while trying to send email with subject \"{0}\". Magic num for log grep {1}'.format(subject, magic)) 

70 flash("Invalid email address - no email specified at all. Trying to send email with subject \"{0}\". Magic number to help identify error: {1}".format(subject, magic), 'error') 

71 return 

72 

73 if app.config.get('CC_ALL_EMAILS_TO', None) is not None: 

74 bcc.append(app.config.get('CC_ALL_EMAILS_TO')) 

75 

76 # Get the body text from the msg_body parameter (for a contact form), 

77 # or render from a template. 

78 # TODO: This could also find and render an HTML template if present 

79 

80 def _msg_to_plaintext(): 

81 if msg_body: 

82 plaintext_body = msg_body 

83 else: 

84 tn = plaintext_template_name if plaintext_template_name else template_name 

85 try: 

86 plaintext_body = render_template(tn, **template_params) 

87 except: 

88 with app.test_request_context(): 

89 plaintext_body = render_template(tn, **template_params) 

90 

91 # strip all the leading and trailing whitespace from the body, which the templates 

92 # leave lying around 

93 plaintext_body = plaintext_body.strip() 

94 

95 return plaintext_body 

96 

97 if html_body_flag and not html_body: 

98 try: 

99 html_body = render_template(template_name, **template_params) 

100 except Exception as e: 

101 logging.WARNING(f"Could not render HTML template for email: {str(e)}") 

102 html_body = None # Explicitly set to None to make the state clear 

103 

104 # Always ensure we have a plaintext body for clients that don't support HTML 

105 # or in case HTML rendering failed 

106 msg_body = _msg_to_plaintext() 

107 

108 # create a message 

109 msg = Message(subject=subject, 

110 recipients=to, 

111 body=msg_body, 

112 html=html_body, 

113 sender=fro, 

114 cc=None, 

115 bcc=bcc, 

116 attachments=files, 

117 reply_to=None, 

118 date=None, 

119 charset=None, 

120 extra_headers=None 

121 ) 

122 

123 try: 

124 mail = Mail(app) 

125 with app.app_context(): 

126 mail.send(msg) 

127 app.logger.info("Email template {0} sent.\nto:{1}\tsubject:{2}".format(template_name, to, subject)) 

128 except Exception as e: 

129 raise EmailException(e) 

130 

131 

132def make_attachment(filename, content_type, data, disposition=None, headers=None): 

133 """ 

134 Provide a function which can make attachments, insulating the caller from the flask-mail 

135 underlying implementation. 

136 

137 :param filename: 

138 :param content_type: 

139 :param data: 

140 :param disposition: 

141 :param headers: 

142 :return: 

143 """ 

144 return Attachment(filename, content_type, data, disposition, headers) 

145 

146 

147def email_archive(data_dir, archv_name): 

148 """ 

149 Compress and email the reports to the specified email address. 

150 :param data_dir: Directory containing the reports 

151 :param archv_name: Filename for the archive and resulting email attachment 

152 """ 

153 import shutil, os 

154 

155 email_to = app.config.get('REPORTS_EMAIL_TO', ['helpdesk@doaj.org']) 

156 email_from = app.config.get('SYSTEM_EMAIL_FROM', 'helpdesk@doaj.org') 

157 email_sub = app.config.get('SERVICE_NAME', '') + ' - generated {0}'.format(archv_name) 

158 msg = "Attached: {0}.zip\n".format(archv_name) 

159 

160 # Create an archive of the reports 

161 archv = shutil.make_archive(archv_name, "zip", root_dir=data_dir) 

162 

163 # Read the archive to create an attachment, send it with the app email 

164 with open(archv, 'rb') as f: 

165 dat = f.read() 

166 attach = [make_attachment(filename=archv_name, content_type='application/zip', data=dat)] 

167 send_mail(to=email_to, fro=email_from, subject=email_sub, msg_body=msg, files=attach) 

168 

169 # Clean up the archive 

170 os.remove(archv)