How to send an email with attachment?

ghz 2days ago ⋅ 4 views

To send an email with an attachment using Python, you can use the smtplib library for sending the email and email library for constructing the message with the attachment. Here's a simple example demonstrating how to send an email with an attachment.

Steps:

  1. Create the email content: Use the MIME classes from the email.mime module to create the message and the attachment.
  2. Attach the file: Read the file as binary and attach it using MIMEBase.
  3. Send the email: Use smtplib.SMTP to connect to the mail server and send the email.

Example Code:

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

# Define the email parameters
sender_email = "your_email@example.com"
receiver_email = "receiver_email@example.com"
subject = "Subject: Email with Attachment"
body = "This is the body of the email."

# Create a MIMEMultipart object to combine the text and the attachment
msg = MIMEMultipart()
msg['From'] = sender_email
msg['To'] = receiver_email
msg['Subject'] = subject

# Attach the body text
msg.attach(MIMEText(body, 'plain'))

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

# Open the file in binary mode and attach it
with open(file_path, "rb") as attachment:
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(attachment.read())
    encoders.encode_base64(part)  # Encode the file in base64
    part.add_header('Content-Disposition', f'attachment; filename={file_path.split("/")[-1]}')
    
    # Attach the file to the message
    msg.attach(part)

# Setup the SMTP server and send the email
try:
    # Establish an SMTP connection (adjust the SMTP server and port accordingly)
    server = smtplib.SMTP('smtp.example.com', 587)  # Change to your SMTP server
    server.starttls()  # Secure the connection

    # Log in to the email account
    server.login("your_email@example.com", "your_password")

    # Send the email
    text = msg.as_string()
    server.sendmail(sender_email, receiver_email, text)
    print("Email sent successfully!")

except Exception as e:
    print(f"Error: {e}")

finally:
    server.quit()

Key Components:

  1. Creating a MIME Multipart Message:

    • MIMEMultipart(): Used to combine multiple parts (like text and file attachments).
    • MIMEText(): To attach text to the email.
    • MIMEBase(): To attach the file as a binary stream.
  2. Attachment Handling:

    • The attachment is read in binary mode using open(file_path, "rb").
    • The content is then encoded with encoders.encode_base64() to ensure that the binary data can be safely sent over email.
  3. SMTP Server Setup:

    • You need to connect to the SMTP server (smtplib.SMTP), authenticate with your email credentials, and send the email using server.sendmail().

Notes:

  • SMTP Server: Replace 'smtp.example.com' with the actual SMTP server you are using (e.g., Gmail: smtp.gmail.com, Outlook: smtp-mail.outlook.com).
  • Authentication: Ensure you replace your_email@example.com and your_password with your email credentials. For Gmail, you may need to use an App Password if 2-factor authentication is enabled.
  • File Attachment: Change file_path to the path of the file you want to send.

Gmail Example:

If you're using Gmail as the SMTP server, the setup would look like this:

server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login("your_email@gmail.com", "your_password")

Important: For Gmail, if you have 2-factor authentication enabled, you will need to generate an App Password from your Google account settings, as normal Gmail passwords won't work for SMTP.

Let me know if you need more details or adjustments!