How to Send Email in Python

  1. Using the smtplib Library
  2. Sending HTML Emails
  3. Sending Emails with Attachments
  4. Conclusion
  5. FAQ
How to Send Email in Python

Sending emails programmatically can be a game-changer for automation and communication in various applications. If you’re looking to send emails using Python, you’re in the right place.

This article will guide you through the process step-by-step, showcasing how to utilize Python’s built-in libraries effectively. Whether you’re sending a simple notification or a more complex message with attachments, Python provides the tools you need. By the end of this article, you’ll have a solid understanding of how to send emails in Python, allowing you to integrate this functionality into your projects seamlessly.

Using the smtplib Library

One of the most common methods to send emails in Python is by using the smtplib library. This library allows you to connect to an SMTP server and send emails from your Python application. Here’s how you can do it:

Python
 pythonCopyimport smtplib
from email.mime.text import MIMEText

sender_email = "your_email@example.com"
receiver_email = "recipient@example.com"
subject = "Test Email"
body = "Hello, this is a test email sent from Python!"

msg = MIMEText(body)
msg['Subject'] = subject
msg['From'] = sender_email
msg['To'] = receiver_email

try:
    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login(sender_email, "your_password")
        server.sendmail(sender_email, receiver_email, msg.as_string())
        print("Email sent successfully!")
except Exception as e:
    print(f"Error: {e}")

Output:

 textCopyEmail sent successfully!

In this example, we first import the necessary modules. We define the sender and receiver’s email addresses, along with the subject and body of the email. The MIMEText class is used to create a text-based email message. After setting up the email, we establish a connection to the SMTP server using smtplib.SMTP. The starttls() method is called to secure the connection, and we log in with the sender’s credentials. Finally, we send the email using sendmail(). If successful, you will see a confirmation message; otherwise, an error will be printed.

Sending HTML Emails

Sometimes, you might want to send HTML-formatted emails to make your messages more visually appealing. Python’s email library makes this easy too. Here’s how you can send an HTML email:

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

sender_email = "your_email@example.com"
receiver_email = "recipient@example.com"
subject = "HTML Email Test"
html = """
<html>
  <body>
    <h1>Hello!</h1>
    <p>This is an <b>HTML</b> email sent from Python!</p>
  </body>
</html>
"""

msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
msg.attach(MIMEText(html, 'html'))

try:
    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login(sender_email, "your_password")
        server.sendmail(sender_email, receiver_email, msg.as_string())
        print("HTML email sent successfully!")
except Exception as e:
    print(f"Error: {e}")

Output:

 textCopyHTML email sent successfully!

In this code snippet, we create a multipart email using MIMEMultipart, which allows us to send both plain text and HTML content. We then define the HTML content, including basic HTML tags. The attach() method is used to add the HTML content to the email. The rest of the process remains the same as sending a plain text email. This method is particularly useful when you want to enhance the email’s appearance with colors, fonts, and images.

Sending Emails with Attachments

Another common requirement is sending emails with attachments. Python allows you to do this easily with the email library. Here’s an example of how to send an email with an attachment:

Python
 pythonCopyimport smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

sender_email = "your_email@example.com"
receiver_email = "recipient@example.com"
subject = "Email with Attachment"
body = "Please find the attached file."
filename = "document.pdf"

msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))

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}')
    msg.attach(part)

try:
    with smtplib.SMTP('smtp.example.com', 587) as server:
        server.starttls()
        server.login(sender_email, "your_password")
        server.sendmail(sender_email, receiver_email, msg.as_string())
        print("Email with attachment sent successfully!")
except Exception as e:
    print(f"Error: {e}")

Output:

 textCopyEmail with attachment sent successfully!

In this example, we first set up the email just like before. However, we also specify the filename of the document we want to attach. We read the file in binary mode and create a MIMEBase object to handle the attachment. The encode_base64() function ensures that the file is encoded properly for email transmission. We then add a header to specify the attachment’s filename and attach it to the email. The rest of the process remains unchanged. This method is incredibly useful for sending reports, images, or any other type of file directly from your Python application.

Conclusion

Sending emails in Python is a straightforward process thanks to libraries like smtplib and email. Whether you need to send simple text emails, HTML-formatted messages, or emails with attachments, Python has the tools to help you accomplish your goals. By following the examples provided in this article, you can easily integrate email functionality into your applications, enhancing communication and automation. With practice, you’ll be able to customize your emails to suit your needs perfectly.

FAQ

  1. How do I set up an SMTP server for sending emails in Python?
    You can use Gmail, Yahoo, or any other email provider that supports SMTP. You’ll need to enable “less secure apps” in your email settings and use the appropriate SMTP server address and port.

  2. Can I send emails without using a password?
    No, most SMTP servers require authentication for security reasons. However, you can use OAuth2 for more secure authentication.

  3. Is it possible to send emails to multiple recipients?
    Yes, you can specify multiple recipients by passing a list of email addresses to the sendmail() method.

  4. How do I handle errors when sending emails?
    You can use try-except blocks to catch exceptions and handle errors gracefully.

  5. Can I send emails using third-party libraries?
    Yes, libraries like yagmail and Flask-Mail can simplify the process of sending emails in Python.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe