Python - Sending Email

Hello there, aspiring Python programmers! Today, we're going to embark on an exciting journey into the world of sending emails using Python. As your friendly neighborhood computer teacher, I'm thrilled to guide you through this process. Trust me, by the end of this tutorial, you'll be sending emails like a pro!

Python - Sending Email

Sending Email in Python

Let's start with the basics. Sending emails in Python is like being a digital postman, but instead of walking door to door, we use a special Python library called smtplib. SMTP stands for Simple Mail Transfer Protocol, which is just a fancy way of saying "the rules for sending mail over the internet".

Here's a simple example to get us started:

import smtplib

sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "your_password"
message = "Hello, this is a test email from Python!"

with smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls()
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)

Let's break this down:

  1. We import the smtplib library.
  2. We set up our sender email, receiver email, and password.
  3. We create a simple message.
  4. We connect to Gmail's SMTP server (more on this later).
  5. We start TLS for security.
  6. We log in to our email account.
  7. Finally, we send the email!

Python smtplib.SMTP() Function

The SMTP() function is like the key to our digital post office. It establishes a connection to the SMTP server we want to use. Here's a more detailed look:

import smtplib

server = smtplib.SMTP('smtp.gmail.com', 587)
print(server.ehlo())
server.starttls()
print(server.ehlo())

In this example:

  • We create an SMTP object for Gmail's server.
  • ehlo() is like saying "hello" to the server.
  • starttls() starts TLS encryption for security.

The Python smtpd Module

While smtplib is for sending emails, smtpd is for receiving them. It's like setting up your own mini email server! Here's a simple example:

import asyncore
from smtpd import SMTPServer

class EmailServer(SMTPServer):
    def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
        print(f'Receiving message from: {peer}')
        print(f'Message addressed from: {mailfrom}')
        print(f'Message addressed to  : {rcpttos}')
        print(f'Message length        : {len(data)}')

server = EmailServer(('localhost', 1025), None)
asyncore.loop()

This sets up a basic email server that prints out information about received emails. It's like having your own personal mail sorting room!

Sending an HTML e-mail using Python

Now, let's make our emails fancy with some HTML:

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

sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "your_password"

message = MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email

text = "Hi there! This is a plain text email."
html = """\
<html>
  <body>
    <p>Hi there!<br>
       This is an <b>HTML</b> email.
    </p>
  </body>
</html>
"""

part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")

message.attach(part1)
message.attach(part2)

with smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls()
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message.as_string())

This example sends an email with both plain text and HTML versions. It's like sending a letter with a fancy envelope!

Sending Attachments as an E-mail

What if we want to send a file along with our email? No problem! Here's how:

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

sender_email = "[email protected]"
receiver_email = "[email protected]"
password = "your_password"

message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Email with attachment"

body = "This is an email with an attachment."
message.attach(MIMEText(body, "plain"))

filename = "document.pdf"  # Replace with your file name
attachment = open(filename, "rb")

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)

with smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls()
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message.as_string())

This script attaches a file to your email. It's like adding a package to your letter!

Sending Email Using Gmail's SMTP Server

Throughout this tutorial, we've been using Gmail's SMTP server. Here's a quick reference table for common SMTP servers:

Email Provider SMTP Server Port
Gmail smtp.gmail.com 587
Outlook smtp-mail.outlook.com 587
Yahoo Mail smtp.mail.yahoo.com 587

Remember, when using Gmail, you might need to enable "Less secure app access" or use an "App Password" if you have 2-Factor Authentication enabled.

And there you have it, folks! You're now equipped to send emails like a Python pro. Remember, with great power comes great responsibility - use your new email-sending skills wisely! Happy coding, and may your emails always reach their destination!

Credits: Image by storyset