0
0
PythonProgramBeginner · 2 min read

Python Program to Send Email Using smtplib

Use Python's smtplib to send an email by creating an SMTP connection, logging in, and calling sendmail() with sender, receiver, and message strings.
📋

Examples

Inputsender='you@example.com', receiver='friend@example.com', subject='Hello', body='Hi there!'
OutputEmail sent successfully
Inputsender='me@gmail.com', receiver='you@gmail.com', subject='Test', body='This is a test email.'
OutputEmail sent successfully
Inputsender='invalid', receiver='friend@example.com', subject='Oops', body='Check sender email'
OutputSMTPAuthenticationError or connection error
🧠

How to Think About It

To send an email in Python, first connect to an SMTP server using smtplib.SMTP. Then log in with your email and password. Next, create the email content as a string with headers like Subject. Finally, use sendmail() to send the email from sender to receiver.
📐

Algorithm

1
Import the smtplib module
2
Set sender email, receiver email, subject, and body
3
Create the email message string with headers
4
Connect to SMTP server and start TLS for security
5
Log in with sender email and password
6
Send the email using sendmail()
7
Close the SMTP connection
💻

Code

python
import smtplib

sender = 'your_email@example.com'
receiver = 'receiver_email@example.com'
password = 'your_password'
subject = 'Test Email'
body = 'Hello, this is a test email sent from Python!'

message = f"Subject: {subject}\n\n{body}"

with smtplib.SMTP('smtp.gmail.com', 587) as server:
    server.starttls()
    server.login(sender, password)
    server.sendmail(sender, receiver, message)

print('Email sent successfully')
Output
Email sent successfully
🔍

Dry Run

Let's trace sending an email with sender='your_email@example.com', receiver='receiver_email@example.com', subject='Test Email', and body='Hello, this is a test email sent from Python!'

1

Create message string

message = 'Subject: Test Email\n\nHello, this is a test email sent from Python!'

2

Connect to SMTP server

Connect to 'smtp.gmail.com' on port 587

3

Start TLS encryption

Secure the connection with starttls()

4

Login

Login with sender='your_email@example.com' and password='your_password'

5

Send email

Send email from sender to receiver with the message

6

Close connection

SMTP connection is closed automatically by with-statement

StepActionValue
1Create messageSubject: Test Email Hello, this is a test email sent from Python!
2Connect SMTPsmtp.gmail.com:587
3Start TLSConnection secured
4Loginyour_email@example.com / your_password
5Send emailFrom your_email@example.com to receiver_email@example.com
6Close connectionConnection closed
💡

Why This Works

Step 1: Create the email message

The message string includes a Subject header followed by two newlines and the email body, which is the format SMTP expects.

Step 2: Connect and secure SMTP

Connecting to the SMTP server and calling starttls() encrypts the connection to keep your login and email safe.

Step 3: Login and send

You log in with your email and password, then use sendmail() to send the email from sender to receiver.

🔄

Alternative Approaches

Using email.message.EmailMessage for better formatting
python
import smtplib
from email.message import EmailMessage

msg = EmailMessage()
msg['Subject'] = 'Hello'
msg['From'] = 'your_email@example.com'
msg['To'] = 'receiver_email@example.com'
msg.set_content('This is a test email using EmailMessage class.')

with smtplib.SMTP('smtp.gmail.com', 587) as server:
    server.starttls()
    server.login('your_email@example.com', 'your_password')
    server.send_message(msg)

print('Email sent successfully')
This method is cleaner and better for complex emails with attachments or HTML.
Using yagmail library for simpler syntax
python
import yagmail

yag = yagmail.SMTP('your_email@example.com', 'your_password')
yag.send('receiver_email@example.com', 'Subject here', 'Body text here')
print('Email sent successfully')
Yagmail simplifies sending emails but requires installing an external package.

Complexity: O(1) time, O(1) space

Time Complexity

Sending an email involves a fixed number of network operations, so time complexity is constant O(1).

Space Complexity

Memory usage is constant O(1) as only a small message string and connection objects are stored.

Which Approach is Fastest?

Using smtplib directly is fast and standard; libraries like yagmail add convenience but may add slight overhead.

ApproachTimeSpaceBest For
smtplib basicO(1)O(1)Simple emails, no extra packages
email.message.EmailMessageO(1)O(1)Complex emails with attachments
yagmail libraryO(1)O(1)Simpler syntax, external dependency
💡
Use starttls() to secure your SMTP connection before logging in.
⚠️
Forgetting to call starttls() causes login failures due to insecure connection.