๐ง How to Send Email with Python
Python makes sending emails straightforward using the smtplib module. Learn to send plain text, HTML emails, and attachments.
Never hardcode passwords. Use environment variables: import os; os.environ.get('EMAIL_PASS')
๐ป Code Example:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# Configuration
sender_email = "pynfinity@gmail.com"
receiver_email = "santoshtvk@gmail.com"
app_password = "your_app_password" # Gmail App Password
# Create message
msg = MIMEMultipart("alternative")
msg["Subject"] = "Hello from Pynfinity!"
msg["From"] = sender_email
msg["To"] = receiver_email
# Plain text + HTML body
text_body = "Hey! Check out pynfinity.com"
html_body = "Hello from Pynfinity!
Visit pynfinity.com
"
msg.attach(MIMEText(text_body, "plain"))
msg.attach(MIMEText(html_body, "html"))
# Send via Gmail SMTP
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login(sender_email, app_password)
server.sendmail(sender_email, receiver_email, msg.as_string())
print("Email sent successfully!")
| Concept | Key Takeaway |
|---|---|
| smtplib.SMTP | Unencrypted SMTP (use port 587 + starttls) |
| smtplib.SMTP_SSL | SSL-encrypted SMTP (more secure, port 465) |
| MIMEText | For simple text/HTML email bodies |
| MIMEMultipart | For emails with multiple parts or attachments |
Keep exploring and happy coding! ๐