refactor(chalice): changed email_handler.py

This commit is contained in:
Taha Yassine Kraiem 2024-02-27 11:43:42 +01:00
parent a690bc779d
commit 72e2900fb9

View file

@ -35,34 +35,32 @@ def __replace_images(HTML):
sub = str(re.findall(pattern_src, sub)[0])
if sub not in swap:
swap.append(sub)
HTML = HTML.replace(sub, f"cid:img-{len(mime_img)}")
cid = f"img-{len(mime_img)}"
HTML = HTML.replace(sub, f"cid:{cid}")
sub = "chalicelib/utils/html/" + sub
with open(sub, "rb") as image_file:
img = base64.b64encode(image_file.read()).decode('utf-8')
mime_img.append(MIMEImage(base64.standard_b64decode(img)))
mime_img[-1].add_header('Content-ID', f'<img-{len(mime_img) - 1}>')
img_data = image_file.read()
mime_img.append(MIMEImage(img_data))
mime_img[-1].add_header('Content-ID', f'<{cid}>')
return HTML, mime_img
def send_html(BODY_HTML, SUBJECT, recipient, bcc=None):
def send_html(BODY_HTML, SUBJECT, recipient):
BODY_HTML, mime_img = __replace_images(BODY_HTML)
if not isinstance(recipient, list):
recipient = [recipient]
msg = MIMEMultipart()
msg = MIMEMultipart('related')
msg['Subject'] = Header(SUBJECT, 'utf-8')
msg['From'] = config("EMAIL_FROM")
msg['To'] = ""
body = MIMEText(BODY_HTML.encode('utf-8'), 'html', "utf-8")
body = MIMEText(BODY_HTML, 'html', "utf-8")
msg.attach(body)
for m in mime_img:
msg.attach(m)
with smtp.SMTPClient() as s:
for r in recipient:
msg.replace_header("To", r)
r = [r]
if bcc is not None and len(bcc) > 0:
r += [bcc]
msg["To"] = r
try:
logging.info(f"Email sending to: {r}")
s.send_message(msg)