import codeengine import json import smtplib import requests from email.message import EmailMessage def send_email(account, to_recipients, cc_recipients=None, subjectLine=None, mailBody=None, domo_file_id=None, domo_access_token_account=None): """ Send an email to multiple recipients. Parameters: - account: account object with SMTP credentials - to_recipients: string of comma-separated email addresses for TO field - cc_recipients: string of comma-separated email addresses for CC field (optional) - subjectLine: email subject - mailBody: html content of the email - domo_file_id: (optional) file id to attach PDF from Domo - domo_access_token_account: account object with Domo access token """ smtp_server = 'smtp.office365.com' smtp_port = 587 # Get Domo Access Token if needed domo_access_token = None if domo_access_token_account: domo_access_token_creds = codeengine.get_account(domo_access_token_account["id"]) domo_access_token = domo_access_token_creds['properties']['domoAccessToken'] # Get SMTP account credentials accountCreds = codeengine.get_account(account["id"]) print(accountCreds) creds = json.loads(accountCreds["properties"]["credentials"]) username = creds["username"] password = creds["password"] # Convert comma-separated strings to lists and strip spaces def parse_recipients(recipients_str): if not recipients_str: return [] return [email.strip() for email in recipients_str.split(",") if email.strip()] to_list = parse_recipients(to_recipients) cc_list = parse_recipients(cc_recipients) # Prepare EmailMessage msg = EmailMessage() msg['Subject'] = subjectLine if subjectLine else "" msg['From'] = username msg['To'] = ", ".join(to_list) if cc_list: msg['Cc'] = ", ".join(cc_list) # Set HTML content msg.set_content(f"""\

{mailBody}

""", subtype='html') # Attach PDF if requested if domo_file_id and domo_access_token: try: url = f"https://domo.domo.com/api/data/v1/data-files/{domo_file_id}" headers = {'content-type': 'application/pdf', "X-Domo-Developer-Token": domo_access_token} response = requests.get(url, headers=headers) if response.status_code == 200: pdf_bytes = response.content print("PDF bytes retrieved successfully") filename = "ACEInternalProcess.pdf" maintype = "application" subtype = "pdf" msg.add_attachment(pdf_bytes, maintype=maintype, subtype=subtype, filename=filename) print(f"Attached file {filename}.") else: print(f"Failed to fetch PDF file. Status Code: {response.status_code}") except Exception as e: print(f"Failed to download or attach file from Domo: {e}") # Combine TO and CC recipients for sending all_recipients = to_list + cc_list # Send the email try: with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login(username, password) server.send_message(msg, from_addr=username, to_addrs=all_recipients) print("Email sent successfully!") except Exception as e: print(f"Failed to send email: {e}")