How to Send Emails Using Python – Step-by-Step Guide

Steps to Send Emails Using Python (with Gmail & SMTP)

Step 1: Import Required Libraries
Step 2: Set Up Your Email Credentials
Enable 2-Step Verification in your Gmail account and create an App Password.
Step 3: Create the Email Message
Step 4: Send the Email Using SMTP
Python Program:
def myfun():
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart

    # Email credentials and details
    sender_email = "sender_email"
    receiver_email = "receiver_email"
    password = "App Password"  # Use App Password if using Gmail with 2FA
    # Note: Change sender_email,receiver_email, App Password
    subject = "Test Email from Python"
    body = "Hello, this is a test email sent from a Python script."

    # Create the email
    message = MIMEMultipart()
    message["From"] = sender_email
    message["To"] = receiver_email
    message["Subject"] = subject

    # Attach the body
    message.attach(MIMEText(body, "plain"))

    # Sending the email using Gmail SMTP
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.starttls()  # Secure the connection
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message.as_string())
        server.quit()
        print("✅ Email sent successfully!")
    except Exception as e:
        print("❌ Failed to send email:", e)

if __name__=="__main__":
    myfun()	

Output:

print("✅ Email sent successfully!")


🔐 Step-by-Step: Enable 2FA & Create App Password in Gmail

✅ Part 1: Enable 2-Step Verification

Go to your Google Account: https://myaccount.google.com
In the left sidebar, click "Security".
Under “Signing in to Google”, click "2-Step Verification".
Click "Get Started" and follow the steps:
Verify your password
Add your phone number
Verify via SMS or call
✅ Part 2: Create an App Password
After enabling 2-Step Verification, return to the Security section.
Under “Signing in to Google”, click "App passwords".
(⚠️ This option appears only after 2-Step Verification is enabled)

Sign in again if prompted.
Under “Select app”, choose Mail.
Under “Select device”, choose Other, then type something like Python Script.
Click “Generate”.
Google will display a 16-character password. Copy it—this is your App Password.
reate an App Password reate an App Password reate an App Password


Contact For Any Query

L.I.G. 625, Road No. 5, behind KLM Shoping Mall, Kukatpally Housing Board Colony, Kukatpally, Hyderabad, Telangana 500072
9010519704
Java training in kukatpally

Enquire Now