Coverage for /home/admin/workarea/git/Velours/python/mtr/ses_mailer.py: 69%

45 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2026-01-26 23:58 +0100

1# -*- coding: utf-8 -*- 

2import base64 

3import os 

4import sib_api_v3_sdk 

5from sib_api_v3_sdk.rest import ApiException 

6import credentials as crd 

7 

8class SesMailer(object): 

9 """ Sends emails via Brevo """ 

10 

11 def __init__(self, api="brevo"): 

12 configuration = sib_api_v3_sdk.Configuration() 

13 configuration.api_key['api-key'] = crd.conf.get('brevo')["API_KEY"] 

14 self._client = sib_api_v3_sdk.ApiClient(configuration) 

15 self._api = sib_api_v3_sdk.TransactionalEmailsApi(self._client) 

16 

17 def send_html_email(self, sender, receivers, subject, body_html, body_text=""): 

18 if isinstance(receivers, list): 

19 to_list = [{"email": r.strip()} for r in receivers] 

20 else: 

21 to_list = [{"email": receivers.strip()}] 

22 

23 email = sib_api_v3_sdk.SendSmtpEmail( 

24 to=to_list, 

25 sender={"email": sender}, 

26 subject=subject, 

27 html_content=body_html if body_html else None, 

28 text_content=body_text if (not body_html) else None 

29 ) 

30 

31 try: 

32 result = self._api.send_transac_email(email) 

33 print("Mail sent:", result) 

34 except ApiException as e: 

35 print("Error send_email:", e) 

36 print(str(e)) 

37 

38 def send_email_with_attachment(self, sender, receivers, subject, body_html="", body_text="", file_path=""): 

39 if isinstance(receivers, list): 

40 to_list = [{"email": r.strip()} for r in receivers] 

41 else: 

42 to_list = [{"email": receivers.strip()}] 

43 

44 attachments = [] 

45 if file_path: 

46 with open(file_path, "rb") as f: 

47 data = f.read() 

48 f.close() 

49 encoded = base64.b64encode(data).decode() 

50# with open(file_path, "rb") as f: 

51# encoded = base64.b64encode(f.read()).decode() 

52 

53 file_name = os.path.basename(file_path) 

54 

55 attachment = sib_api_v3_sdk.SendSmtpEmailAttachment( 

56 name=file_name, 

57 content=encoded 

58 ) 

59 if encoded != '': 

60 attachments.append(attachment) 

61 

62 if len(attachments) == 0: 

63 email = sib_api_v3_sdk.SendSmtpEmail( 

64 to=to_list, 

65 sender={"email": sender}, 

66 subject=subject, 

67 html_content=body_html if body_html else None, 

68 text_content=body_text if (not body_html) else None) 

69 else: 

70 email = sib_api_v3_sdk.SendSmtpEmail( 

71 to=to_list, 

72 sender={"email": sender}, 

73 subject=subject, 

74 html_content=body_html if body_html else None, 

75 text_content=body_text if (not body_html) else None, 

76 attachment=attachments) 

77 

78 try: 

79 result = self._api.send_transac_email(email) 

80 print("Mail sent:", result) 

81 except ApiException as e: 

82 print("Error send_email_with_attachment:", e) 

83 print(str(e))