Thursday, January 9, 2025
HomeProgrammingHow to send an email with Python?

How to send an email with Python?

You can send an email with Python using the smtplib library, which provides tools to connect to an SMTP server and send emails. Here’s a step-by-step guide:

Step 1: Set Up Your Email Account

  • You need the following details of your email account:
    • SMTP Server: E.g., Gmail’s SMTP server is smtp.gmail.com.
    • Port: Typically 587 for TLS or 465 for SSL.
    • Username: Your email address.
    • Password: Your email account password or app-specific password (for security reasons).

Step 2: Install Required Libraries

In addition to smtplib, you can use email for composing messages. Both libraries are included in Python’s standard library, so no extra installation is required.

Step 3: Send an Email

Basic Example

This example sends a plain-text email using Gmail’s SMTP server.

import smtplib
from email.mime.text import MIMEText

# Email details
sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "your_password"  # Use an app-specific password if needed.

# Email content
subject = "Test Email"
body = "Hello, this is a test email sent using Python!"

# Create MIMEText email object
message = MIMEText(body, "plain")
message["Subject"] = subject
message["From"] = sender_email
message["To"] = receiver_email

# Send the email
try:
    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()  # Secure the connection
        server.login(sender_email, password)  # Login to your email account
        server.send_message(message)  # Send the email
    print("Email sent successfully!")
except Exception as e:
    print(f"Failed to send email: {e}")

Step 4: Sending HTML Emails

To send an email with HTML content, use MIMEText with the "html" subtype.

from email.mime.text import MIMEText

# Email content (HTML)
html_body = """
<html>
    <body>
        <h1 style="color: blue;">Hello!</h1>
        <p>This is an <b>HTML email</b> sent using Python.</p>
    </body>
</html>
"""

# Create MIMEText email object with HTML
message = MIMEText(html_body, "html")
message["Subject"] = "HTML Email Test"
message["From"] = sender_email
message["To"] = receiver_email

# Send as before

Step 5: Attach Files to the Email

To attach files, use the MIMEMultipart class.

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

# Create a multipart message
message = MIMEMultipart()
message["Subject"] = "Email with Attachment"
message["From"] = sender_email
message["To"] = receiver_email

# Email body
body = "Please find the attached file."
message.attach(MIMEText(body, "plain"))

# Attach a file
filename = "example.txt"  # Replace with your file path
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)

# Send the email
try:
    with smtplib.SMTP("smtp.gmail.com", 587) as server:
        server.starttls()
        server.login(sender_email, password)
        server.send_message(message)
    print("Email with attachment sent successfully!")
except Exception as e:
    print(f"Failed to send email: {e}")

Step 6: Use Environment Variables for Security

For better security, avoid hardcoding sensitive information (e.g., email passwords). Use environment variables.

See also  How do I Replicate a \t Tab Space in HTML?

Example:

import os

# Get sensitive data from environment variables
sender_email = os.getenv("EMAIL_ADDRESS")
password = os.getenv("EMAIL_PASSWORD")

Troubleshooting

  1. Enable “Less Secure Apps”:
    • For Gmail, you may need to enable “less secure apps” or generate an app password.
    • Enable it from Google Account Security.
  2. Check SMTP Settings:
    • Ensure you’re using the correct SMTP server and port for your email provider.
  3. Firewall/Antivirus:
    • Some firewalls or antivirus programs may block outgoing emails. Ensure the Python script is allowed to send emails.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x