Cipher
Cipher

Reputation: 1

How to add text to the body of an email in Python using MIMEMultipart

I am trying to send an email through Python to multiple recipients, and each recipient receives a different attachment on that email. I have managed to do this. The code below also lets me specify the subject line of the email. However, my question is how to add to the existing code I have below so that I am able to add some text within the body of the email. Ideally, this text would be sent to all recipients. I have been using MIMEMultipart and MIMEBase. Thank you!

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

def send_email(receiver_email, attachment_path):
    sender_email = "********@gmail.com"
    password = "**** **** **** ****"  # Enter your email password here

    # Set up the MIME
    message = MIMEMultipart()
    message['From'] = sender_email
    message['To'] = receiver_email
    message['Subject'] = "Notes"

    # Attach the file to the email
    with open(attachment_path, "rb") as attachment:
        part = MIMEBase("application", "octet-stream")
        part.set_payload(attachment.read())
    
    # Encode the attachment and add headers
    encoders.encode_base64(part)
    part.add_header(
        "Content-Disposition",
        f"attachment; filename= {attachment_path.split('/')[-1]}",
    )
    message.attach(part)

    # Connect to the SMTP server and send the email
    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())

# List of recipients and corresponding file paths
recipients = {
    "***[Recipient1]***@gmail.com": "/Users/***/Desktop/[file attachment]",
    "***[Recipient2]***@gmail.com": "/Users/***/Desktop/[file attachment]",
}

# Sending emails to each recipient with corresponding attachment
for recipient, attachment_path in recipients.items():
    send_email(recipient, attachment_path)

Upvotes: 0

Views: 82

Answers (0)

Related Questions