|
| 1 | +import os |
| 2 | +import boto3 |
| 3 | +from email.mime.multipart import MIMEMultipart |
| 4 | +from email.mime.text import MIMEText |
| 5 | +from email.mime.application import MIMEApplication |
| 6 | +from dotenv import load_dotenv |
| 7 | + |
| 8 | +load_dotenv() |
| 9 | + |
| 10 | + |
| 11 | +def send_ses_email( |
| 12 | + subject, body_text, body_html, sender_email, recipient_emails, attachment=None |
| 13 | +): |
| 14 | + # Create a multipart/mixed parent container |
| 15 | + msg = MIMEMultipart("mixed") |
| 16 | + msg["Subject"] = subject |
| 17 | + msg["From"] = sender_email |
| 18 | + msg["To"] = ", ".join(recipient_emails) |
| 19 | + |
| 20 | + # Add body to email |
| 21 | + msg_body = MIMEMultipart("alternative") |
| 22 | + textpart = MIMEText(body_text.encode("utf-8"), "plain", "utf-8") |
| 23 | + htmlpart = MIMEText(body_html.encode("utf-8"), "html", "utf-8") |
| 24 | + |
| 25 | + msg_body.attach(textpart) |
| 26 | + msg_body.attach(htmlpart) |
| 27 | + msg.attach(msg_body) |
| 28 | + |
| 29 | + # Attachment |
| 30 | + if attachment: |
| 31 | + with open(attachment, "rb") as f: |
| 32 | + part = MIMEApplication(f.read()) |
| 33 | + part.add_header( |
| 34 | + "Content-Disposition", |
| 35 | + "attachment", |
| 36 | + filename=os.path.basename(attachment), |
| 37 | + ) |
| 38 | + msg.attach(part) |
| 39 | + |
| 40 | + # Connect to AWS SES |
| 41 | + client = boto3.client( |
| 42 | + "ses", |
| 43 | + aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"), |
| 44 | + aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"), |
| 45 | + region_name=os.getenv("AWS_REGION"), |
| 46 | + ) |
| 47 | + |
| 48 | + # Try to send the email. |
| 49 | + try: |
| 50 | + response = client.send_raw_email( |
| 51 | + Source=sender_email, |
| 52 | + Destinations=recipient_emails, |
| 53 | + RawMessage={"Data": msg.as_string()}, |
| 54 | + ) |
| 55 | + except Exception as e: |
| 56 | + print(e) |
| 57 | + return False |
| 58 | + return True |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + |
| 63 | + subject = "Your magic link to log in to Atlas" |
| 64 | + body_text = "Content of your email." |
| 65 | + body_html = """<html> |
| 66 | + <head></head> |
| 67 | + <body> |
| 68 | + <h1>Welcome to Atlas!</h1> |
| 69 | + <p>Click <a href='https://atlas.scaledhumanity.org'>here</a> to log in</p> |
| 70 | + </body> |
| 71 | + </html>""" |
| 72 | + sender_email = "noreply@scaledhumanity.org" |
| 73 | + recipient_emails = ["nakhaeiamirhossein@gmail.com"] |
| 74 | + |
| 75 | + # Send the email |
| 76 | + send_ses_email(subject, body_text, body_html, sender_email, recipient_emails) |
0 commit comments