✅ 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:
-
Go to your Google Account
-
Enable Two-Step Verification
-
Open Security → App Passwords
-
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