What you will read?
Sending emails through Google’s SMTP server is one of the most reliable and secure methods for web applications, contact forms, and automated notifications.
Step 1: Enable SMTP Access in Gmail
To use Gmail’s SMTP server, you must enable 2-Step Verification and generate an App Password. This password replaces your regular Gmail password when authenticating via SMTP.
smtp_server = "smtp.gmail.com" port = 587 sender_email = "[email protected]" app_password = "your_app_password"
Step 2: Secure Connection with TLS
To protect your email credentials and ensure encrypted communication with Gmail’s SMTP server, it’s essential to initiate a TLS-secured session before sending any data.
import smtplib server = smtplib.SMTP(smtp_server, port) server.starttls() server.login(sender_email, app_password)
Step 3: Send an Email via SMTP
After establishing a secure connection and authenticating with Gmail’s SMTP server, you can send a plain-text email by composing the message and using the sendmail method to deliver it to the recipient.
receiver_email = "[email protected]" subject = "Test Email from Google SMTP" body = "This is a test email sent using Gmail SMTP server." message = f"Subject: {subject}\n\n{body}" server.sendmail(sender_email, receiver_email, message) server.quit()
Step 4: Handle Errors Gracefully
To ensure your email-sending process is reliable and doesn’t crash unexpectedly, wrap your SMTP logic in a try-except block to catch authentication failures, connection issues, or other runtime errors.
try:
server = smtplib.SMTP(smtp_server, port)
server.starttls()
server.login(sender_email, app_password)
server.sendmail(sender_email, receiver_email, message)
except Exception as e:
print(f"Error: {e}")
finally:
server.quit()
Step 5: Security Tips and Email Deliverability
To keep your Gmail account safe and ensure your emails reach inboxes instead of spam folders, follow essential security practices and optimize your sending reputation.
# Tips (not code): # - Use App Passwords instead of your main Gmail password # - Set up SPF and DKIM records for your domain # - Avoid sending bulk emails from personal Gmail accounts # - Personalize your messages to improve engagement and reduce spam risk
Step 6: Use HTML Content in Emails
To create visually appealing emails with formatting, links, and styling, you can embed HTML content directly into your message using MIME components.
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
message = MIMEMultipart("alternative")
message["Subject"] = "HTML Email Test"
message["From"] = sender_email
message["To"] = receiver_email
html = """\
<html>
<body>
<h1>Hello!</h1>
<p>This is an <b>HTML</b> email sent via <a href="https://smtp.gmail.com">Google SMTP</a>.</p>
</body>
</html>
"""
part = MIMEText(html, "html")
message.attach(part)
server.sendmail(sender_email, receiver_email, message.as_string())
Step 7: Send Email with Attachments
To include files like PDFs, images, or documents in your emails, you can attach them using MIME components to ensure proper formatting and delivery across all email clients.
from email.mime.application import MIMEApplication
filename = "document.pdf"
with open(filename, "rb") as attachment:
part = MIMEApplication(attachment.read(), Name=filename)
part['Content-Disposition'] = f'attachment; filename="{filename}"'
message.attach(part)
server.sendmail(sender_email, receiver_email, message.as_string())




