Here is how to send an email from Gmail in Python.

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

# Set up the SMTP server details
smtp_server = ''
smtp_port = 587  # Gmail SMTP port

# Your Gmail credentials
sender_email = '[email protected]'
sender_password = 'your_password'

# Recipient email address
recipient_email = '[email protected]'

# Create a message object
message = MIMEMultipart()
message['From'] = sender_email
message['To'] = recipient_email
message['Subject'] = 'Test Email from Python'

# The body of the email
body = 'This is a test email sent from Python.'
message.attach(MIMEText(body, 'plain'))

# Connect to the SMTP server
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()  # Start TLS encryption
server.login(sender_email, sender_password)

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

# Close the connection

print("Email sent successfully!") 


An email will be sent to the email address [email protected] with the email subject "Test Email for Python" and the text "This is a test email sent from Python". 

  • Replace '[email protected]' and 'your_password' with your Gmail address and password.
  • You need a Gmail app password as the password. To create an app password, go to your Google account settings at Then, search for "app password" in the search bar. Then, click over the "App Password" menu item and follow the instructions. For this to work, you should have first enabled 2-factor verification for your Google account. 
  • Replace '[email protected]' with the email address of the recipient.

Recommended Course

Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.