Python code to send mail from gmail

 import smtplib

from email.mime.text import MIMEText

# Email and app password setup

sender_email = "sender@gmail.com"

receiver_email = "receiver@gmail.com"

password = "gmailapppassword"  # Use Gmail App Password, not your normal password

# Email content

subject = "Test Email from Python"

body = "This is a test email sent from a Python script."


# Create MIMEText object

msg = MIMEText(body)

msg['Subject'] = subject

msg['From'] = sender_email

msg['To'] = receiver_email


# Connect to Gmail SMTP server and send email

try:

    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp_server:

        smtp_server.login(sender_email, password)

        smtp_server.sendmail(sender_email, receiver_email, msg.as_string())

    print("Email sent successfully!")

except Exception as e:

    print(f"Failed to send email: {e}")

Comments