|
| 1 | +import os |
| 2 | +import pandas as pd |
| 3 | +import logging |
| 4 | +from email.mime.text import MIMEText |
| 5 | +from email.mime.multipart import MIMEMultipart |
| 6 | +from google.oauth2.credentials import Credentials |
| 7 | +from google.auth.transport.requests import Request |
| 8 | +from google_auth_oauthlib.flow import InstalledAppFlow |
| 9 | +from googleapiclient.discovery import build |
| 10 | +from tenacity import retry, stop_after_attempt, wait_fixed |
| 11 | + |
| 12 | +# Setup logging |
| 13 | +logging.basicConfig( |
| 14 | + filename='email_sender.log', |
| 15 | + level=logging.INFO, |
| 16 | + format='%(asctime)s:%(levelname)s:%(message)s' |
| 17 | +) |
| 18 | + |
| 19 | +SCOPES = ['https://www.googleapis.com/auth/gmail.send'] |
| 20 | + |
| 21 | +def authenticate_gmail(): |
| 22 | + creds = None |
| 23 | + if os.path.exists('token.json'): |
| 24 | + creds = Credentials.from_authorized_user_file('token.json', SCOPES) |
| 25 | + if not creds or not creds.valid: |
| 26 | + if creds and creds.expired and creds.refresh_token: |
| 27 | + creds.refresh(Request()) |
| 28 | + else: |
| 29 | + flow = InstalledAppFlow.from_client_secrets_file( |
| 30 | + 'credentials.json', SCOPES) |
| 31 | + creds = flow.run_local_server(port=0) |
| 32 | + with open('token.json', 'w') as token: |
| 33 | + token.write(creds.to_json()) |
| 34 | + return build('gmail', 'v1', credentials=creds) |
| 35 | + |
| 36 | +def create_message(sender, to, subject, body, cc=None, bcc=None): |
| 37 | + message = MIMEMultipart() |
| 38 | + message['to'] = to |
| 39 | + message['from'] = sender |
| 40 | + message['subject'] = subject |
| 41 | + if cc: |
| 42 | + message['cc'] = cc |
| 43 | + if bcc: |
| 44 | + message['bcc'] = bcc |
| 45 | + message.attach(MIMEText(body, 'plain')) |
| 46 | + return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()} |
| 47 | + |
| 48 | +@retry(stop=stop_after_attempt(3), wait=wait_fixed(5)) |
| 49 | +def send_email(service, sender, to, subject, body, cc=None, bcc=None): |
| 50 | + try: |
| 51 | + msg = create_message(sender, to, subject, body, cc, bcc) |
| 52 | + service.users().messages().send(userId='me', body=msg).execute() |
| 53 | + logging.info(f"Email sent to {to} with subject '{subject}'") |
| 54 | + except Exception as e: |
| 55 | + logging.error(f"Error sending email to {to}: {str(e)}") |
| 56 | + raise |
| 57 | + |
| 58 | +def send_bulk_emails(csv_file='recipients.csv'): |
| 59 | + service = authenticate_gmail() |
| 60 | + sender = "me" |
| 61 | + df = pd.read_csv(csv_file) |
| 62 | + for index, row in df.iterrows(): |
| 63 | + send_email( |
| 64 | + service, |
| 65 | + sender, |
| 66 | + row['email'], |
| 67 | + row['subject'], |
| 68 | + row['body'], |
| 69 | + cc=row.get('cc'), |
| 70 | + bcc=row.get('bcc') |
| 71 | + ) |
0 commit comments