File size: 1,607 Bytes
6d12745
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import os
import smtplib
from email.mime.text import MIMEText
from dotenv import load_dotenv

# Load variables from .env if present
load_dotenv()

def send_email(to_email, subject, message_body, cc_emails=None, bcc_emails=None):
    gmail_user = "satyamrahangdale196@gmail.com"
    app_password = os.environ.get("APP_PASSWORD")

    if not gmail_user or not app_password:
        print("Environment variables GMAIL_USER or APP_PASSWORD not set.")
        return False

    try:
        msg = MIMEText(message_body)
        msg['Subject'] = subject
        msg['From'] = gmail_user
        msg['To'] = to_email

        # Add CC if present
        if cc_emails:
            msg['Cc'] = ", ".join(cc_emails)

        # Combine all recipients for sending
        recipients = [to_email]
        if cc_emails:
            recipients += cc_emails
        if bcc_emails:
            recipients += bcc_emails

        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
            smtp.login(gmail_user, app_password)
            smtp.sendmail(gmail_user, recipients, msg.as_string())

        print("Email sent successfully.")
        return True

    except Exception as e:
        print(f"Error sending email: {e}")
        return False

# Example usage
# send_email(
#     to_email="satyamrahangdale196@kgpian.iitkgp.ac.in",
#     subject="Auto email API TESTING : Email with CC and BCC",
#     message_body="This message has been sent for testing CC and BCC support!",
#     cc_emails=["raianand.1991@gmail.com","satyamrahangdale207@gmail.com"],
#     bcc_emails=["pedanticsatoshi0@getsafesurfer.com"]
# )