Python script to send an email (Using your GMail account)

To send an email using Python, you can use the smtplib library, which is part of the standard library, along with the email library for constructing the email message. Here’s a basic example of a Python script to send an email using a Gmail account:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(subject, body, to_email, smtp_server, smtp_port, sender_email, sender_password):
    # Create the MIME object
    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = to_email
    message['Subject'] = subject

    # Attach the body of the email
    message.attach(MIMEText(body, 'plain'))

    # Connect to the SMTP server
    with smtplib.SMTP(smtp_server, smtp_port) as server:
        # Login to the email account
        server.starttls()
        server.login(sender_email, sender_password)

        # Send the email
        server.sendmail(sender_email, to_email, message.as_string())

    print("Email sent successfully.")

# Set your email configuration
subject = "Test Email"
body = "This is a test email sent from a Python script."
to_email = "[email protected]"
smtp_server = "smtp.gmail.com"
smtp_port = 587
sender_email = "[email protected]"
sender_password = "your_email_password"

# Call the function to send the email
send_email(subject, body, to_email, smtp_server, smtp_port, sender_email, sender_password)

Note: Make sure to replace the placeholder values for to_email, sender_email, and sender_password with your recipient’s email address, your Gmail email address, and your Gmail password, respectively. Keep in mind that storing email passwords in code is not secure. It would help if you considered using environment variables or a configuration file to manage sensitive information in a production environment. Also, be aware that Google may require you to enable “Less secure app access” in your Google account settings to allow sending emails using this method.

Please be cautious with your email credentials and avoid sharing or hardcoding them directly in the script for security reasons.