How to send a attatchment in mail using python

To send an email with an attachment using Python, you can use the smtplib library to connect to a mail server and the email library to create the email message. Here's an example code snippet:

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

# Define the email settings
SMTP_SERVER = "your_smtp_server"
SMTP_PORT = 587
FROM_EMAIL = "your_from_email"
TO_EMAIL = "your_to_email"
PASSWORD = "your_email_password"

# Define the attachment file
ATTACHMENT_FILE = "path/to/your/file.txt"

# Create the email message
msg = MIMEMultipart()
msg["From"] = FROM_EMAIL
msg["To"] = TO_EMAIL
msg["Subject"] = "Test Email with Attachment"
msg["Date"] = formatdate(localtime=True)

# Add the attachment
with open(ATTACHMENT_FILE, "rb") as f:
    part = MIMEBase("application", "octet-stream")
    part.set_payload(f.read())
    encoders.encode_base64(part)
    part.add_header("Content-Disposition", f"attachment; filename={ATTACHMENT_FILE}")
    msg.attach(part)

# Create the text body of the email
body = "This is a test email with an attachment."
msg.attach(MIMEText(body, "plain"))

# Connect to the mail server
server = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
server.starttls()
server.login(FROM_EMAIL, PASSWORD)

# Send the email
server.sendmail(FROM_EMAIL, TO_EMAIL, msg.as_string())

# Close the connection
server.quit()

This code creates an email message with a text body and an attachment, and sends it to the specified recipient using the specified SMTP server.

Here's a breakdown of the code:

  1. We import the necessary libraries: smtplib for connecting to the mail server, email for creating the email message, and encoders for encoding the attachment.
  2. We define the email settings: SMTP server, port, from email, to email, and password.
  3. We define the attachment file.
  4. We create the email message using MIMEMultipart.
  5. We add the attachment to the email message using MIMEBase.
  6. We create the text body of the email using MIMEText.
  7. We connect to the mail server using smtplib.
  8. We login to the mail server using server.login.
  9. We send the email using server.sendmail.
  10. We close the connection using server.quit.

Note that you'll need to replace the placeholders (your_smtp_server, your_from_email, your_to_email, your_email_password, and path/to/your/file.txt) with your actual email settings and attachment file path.