from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from email.mime.text import MIMEText import smtplib from jinja2 import Template from datetime import datetime import os import json # # SMTP details from environment variables # smtp_server = os.environ.get("MAIL_SERVER") # smtp_port = os.environ.get("MAIL_PORT") # from_sender = os.environ.get("MAIL_FROM") # to_addr = os.environ.get("MAIL_TO") # bcc_addr = os.environ.get("MAIL_BCC") with open('config.json', 'r') as f: config = json.load(f) smtp_server = config['mail']["server"] smtp_port = config['mail']["port"] to_addr = config['mail']["to"] bcc_addr = config['mail']["bcc"] from_sender = config['mail']['sender'] def send_mail(to: str = to_addr, bcc: str = bcc_addr, message: str = '', path: str = '', server: str = smtp_server, port: str = smtp_port, sender: str = from_sender) -> None: # Create a multipart message date_now = datetime.now().strftime("%Y.%m.%d") msg = MIMEMultipart() body_part = MIMEText(message, 'html') msg['Subject'] = f"Delphi Daily Data Alert: {date_now}" msg['From'] = sender msg['To'] = to recipients = msg['To'].split(',') + bcc.split(',') # Add body to email msg.attach(body_part) csv_files = os.listdir(path) # loop over files for file_name in csv_files: with open(f"{path}/{file_name}", 'rb') as file: # Attach the file with filenames to the email msg.attach(MIMEApplication(file.read(), Name=file_name)) # Create SMTP object mail_server = smtplib.SMTP(server, port) mail_server.sendmail(msg['From'], recipients, msg.as_string()) mail_server.quit() def html_generate(message_dict): html_template = open('templates/email_body.html').read() template = Template(html_template) result = template.render(message_dict=message_dict) return result if __name__ == '__main__': pass # send_mail(to=to_addr, bcc=bcc_addr, path='files/2021-05-06', message="Hello there", server=smtp_server, port=smtp_port)