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

How to Send Email Attachments Using Python?

DDD
Release: 2024-12-12 15:58:15
Original
134 people have browsed it

How to Send Email Attachments Using Python?

How to send email attachments with Python

Sending email attachments using Python might seem daunting, especially for beginners. Let's break it down step by step.

The smtplib library is commonly used for sending emails in Python. Here's a simplified example that also includes attachment functionality:

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

Let's decode the code:

  • Create a MIMEMultipart object to represent the email message.
  • Set the sender's and recipient's email addresses, subject, and date.
  • Use MIMEText to create the email body and attach it to the email message.
  • Loop through the attachment files (if any) and use MIMEApplication to prepare them as attachments.
  • Attach the prepared attachments to the email message.
  • Create an SMTP object and connect to the specified email server.
  • Send the email message using smtp.sendmail() and close the connection.

Using this script, you can easily attach files to emails and send them using Python. Remember to replace the placeholder values (e.g., sender, recipients, subject, etc.) with your own information.

The above is the detailed content of How to Send Email Attachments Using Python?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template