|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +This script sends templated emails to a list of recipients from a CSV file. |
| 4 | +
|
| 5 | +USAGE: |
| 6 | + python interest_form_emails.py <path_to_csv_file> |
| 7 | +
|
| 8 | +REQUIREMENTS: |
| 9 | + - CSV file must contain an "Email" column with valid email addresses |
| 10 | +""" |
| 11 | + |
| 12 | +import os |
| 13 | +import sys |
| 14 | +import csv |
| 15 | +import time |
| 16 | +from sendgrid import SendGridAPIClient |
| 17 | +from sendgrid.helpers.mail import Mail |
| 18 | + |
| 19 | +FROM_EMAIL = "contact@mchacks.ca" |
| 20 | +TEMPLATE_ID = "d-8cbb9f9e07f04712bc88aecba33d49f3" |
| 21 | + |
| 22 | + |
| 23 | +def send_email(to_email): |
| 24 | + |
| 25 | + message = Mail( |
| 26 | + from_email=FROM_EMAIL, |
| 27 | + to_emails=to_email, |
| 28 | + ) |
| 29 | + message.template_id = TEMPLATE_ID |
| 30 | + |
| 31 | + try: |
| 32 | + sg = SendGridAPIClient(os.getenv("SENDGRID_API_KEY")) |
| 33 | + response = sg.send(message) |
| 34 | + return True |
| 35 | + except Exception as e: |
| 36 | + print(f"Error sending to {to_email}: {e}") |
| 37 | + return False |
| 38 | + |
| 39 | + |
| 40 | +def parse_csv(csv_filename): |
| 41 | + if not os.path.exists(csv_filename): |
| 42 | + print(f"Error: File '{csv_filename}' not found") |
| 43 | + return |
| 44 | + |
| 45 | + sent_count = 0 |
| 46 | + failed_count = 0 |
| 47 | + |
| 48 | + try: |
| 49 | + with open(csv_filename, "r", newline="", encoding="utf-8") as csvfile: |
| 50 | + reader = csv.DictReader(csvfile) |
| 51 | + |
| 52 | + for _, row in enumerate(reader, start=1): |
| 53 | + email = row.get("Email", "").strip() |
| 54 | + |
| 55 | + if not email or "@" not in email: |
| 56 | + continue |
| 57 | + |
| 58 | + if send_email(email): |
| 59 | + sent_count += 1 |
| 60 | + else: |
| 61 | + failed_count += 1 |
| 62 | + |
| 63 | + time.sleep(0.1) # Add delay to avoid rate limiting |
| 64 | + |
| 65 | + print(f"\nSent: {sent_count} | Failed: {failed_count}") |
| 66 | + |
| 67 | + except Exception as e: |
| 68 | + print(f"Error: {e}") |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == "__main__": |
| 72 | + parse_csv(sys.argv[1]) |
0 commit comments