How to Send Emails Using Python – A Complete Guide

 

✅ 1. Prerequisites

Before writing the code, make sure you have:

✔ Python installed
✔ A Gmail account (or any email service)
✔ An App Password (for Gmail users with 2-Step Verification)


✅ 2. Create an App Password (Gmail Users)

Since Google blocks less secure login methods, you must use an app password instead of your regular Gmail password.

Steps:

  1. Go to your Google Account

  2. Enable Two-Step Verification

  3. Open Security → App Passwords

  4. Generate a password and use it in the code


✅ 3. Send a Simple Email Using Python

Here’s the most common and easy method using smtplib and email modules:

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

# Email account credentials
sender_email = "your_email@gmail.com"
password = "your_app_password"
receiver_email = "recipient@example.com"

# Create the email
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Test Email from Python"

# Email body
body = "Hello! This is a test email sent using Python."
message.attach(MIMEText(body, "plain"))

try:
    # Connect to Gmail's SMTP server
    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())
    print("✅ Email sent successfully!")
    server.quit()
except Exception as e:
    print(f"❌ Error: {e}")

✅ 4. Sending an HTML Email

You can send formatted messages by changing the body type:

html_body = """
<html>
<body>
  <h2>Hello!</h2>
  <p>This is an <b>HTML</b> email sent using Python.</p>
</body>
</html>
"""

message.attach(MIMEText(html_body, "html"))

✅ 5. Add Attachments (Optional)

To send a file like a PDF or image, use this snippet:

from email.mime.base import MIMEBase
from email import encoders

filename = "sample.pdf"  # file to send

with open(filename, "rb") as attachment:
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

encoders.encode_base64(part)
part.add_header(
    "Content-Disposition",
    f"attachment; filename={filename}",
)

message.attach(part)

✅ 6. Common SMTP Settings

Email Service SMTP Server Port
Gmail smtp.gmail.com 587
Outlook smtp.office365.com 587
Yahoo smtp.mail.yahoo.com 587

Replace these in the server = smtplib.SMTP("smtp.gmail.com", 587) line if needed.


✅ Conclusion

Sending emails using Python is simple and powerful. With smtplib and email modules, you can:

✔ Send plain text emails
✔ Add HTML formatting
✔ Attach files
✔ Automate notifications and reports

Leave a Reply

Your email address will not be published. Required fields are marked *

Company

Hello! I’m a passionate automation enthusiast with a background in Python programming and UiPath automation. With several years of experience in the insurance industry, I’ve witnessed firsthand the challenges organizations face in streamlining processes and managing data efficiently.

Features

Most Recent Posts

eBook App for FREE

Lorem Ipsum is simply dumy text of the printing typesetting industry lorem.

Category

Unlock the synergy of Python and UiPath to elevate your automation projects 

My skills

Automation

Illustrator designing

Web developing

Content writing

Learn from ME

Uipath Automation

Python programing

latest trends in IT

Designs using illustrator

Purchase

Automation projects

Graphic designs

web Boiler plates

Newsletter

Help

Copyright

Privacy Policy

© 2024 created by SubinSuresh