Home > Backend Development > Python Tutorial > How to Send Email Attachments Using Python's smtplib?

How to Send Email Attachments Using Python's smtplib?

Barbara Streisand
Release: 2024-12-17 00:16:25
Original
521 people have browsed it

How to Send Email Attachments Using Python's smtplib?

Sending Attachments with Python's smtplib

Sending emails with Python's smtplib is a breeze, but including attachments can seem a bit cryptic for beginners. Here's a straightforward explanation to help you master this task.

Code Snippet:

Let's start with a simple code snippet:

import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate

def send_mail(send_from, send_to, subject, text, files=None,
              server="127.0.0.1"):
    assert isinstance(send_to, list)

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)


    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()
Copy after login

Explanation:

  1. MIMEMultipart: MIME messages support multiple MIME parts and form the outermost layer.
  2. MIMEText: The email's body is created as MIMEText containing the text.
  3. MIMEApplication: The file to be attached is treated as MIMEApplication and its name is extracted using basename(f).
  4. Content-Disposition: This field configures the attachment's handling by email clients, specifying it as an attachment with its name.
  5. SMTP: An SMTP object is set up to connect to a mail server ("127.0.0.1" by default).
  6. sendmail: The email is sent using the sendmail method with the sender, recipients, and message.

The above is the detailed content of How to Send Email Attachments Using Python's smtplib?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template