[Python] How to add an attachment to a python email script used for sending mass emails to...

Discussão em 'Python' iniciado por Stack, Março 2, 2025.

  1. Stack

    Stack Membro Participativo

    I wrote a python script that parses a csv for email addresses and then sends an email message to each email address. It has worked for me for regular emails, I just need help sorting out if there's a way to add a pdf attachment to the email template. Is there a way to add in a prompt to add attachments without altering my existing script too much?

    I'm mainly concerned with keeping the pre-send script the same as it serves a specific purpose of parsing the csv for email address that meet the parameters I've set.

    import os
    import win32com.client as win32
    import pandas as pd
    import datetime


    # Define today's date
    today = datetime.date.today().strftime('%m/%d/%Y')

    # Read the CSV file
    df = pd.read_csv('exhibitorlist.csv')
    print(df)

    # Set up outlook
    outlook = win32.Dispatch('Outlook.Application')
    namespace = outlook.GetNamespace('MAPI')
    sent_folder = namespace.GetDefaultFolder(5)
    inbox_folder = namespace.GetDefaultFolder(6)

    # Define email template with placeholders for variables
    email_template = """
    EMAIL TEMPLATE HERE - I've removed the text for this purpose

    <p></p>

    """


    # Define send email fucntion
    def send_email(to, body, subject):
    mail = outlook.CreateItem(0)
    mail.To = '{}'.format(email_address)
    mail.Subject = "Exhibitor Email"
    attachment = mail.Attachments.Add("C:/Users/User/AppData/Local/Programs/Python/Python311/my_sig_files/logo.png")
    attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001FFS", "my_sig")
    mail.HTMLBody = body + "<html><body><img style='width: 100px' src=""cid:my_sig""></body></html>"
    mail.Send()

    for index, row in df.iterrows():
    check_on = row['check_on']
    designation = row['designation']
    email_address = row['email_address']
    action = row['action']

    if check_on == today and designation == "auto" and action == "send":

    to = '{}'.format(email_address)
    body = email_template
    subject = "Exhibitor Email"

    send_email(to, body, subject)

    df.at[index, 'check_on'] = (datetime.datetime.today() + datetime.timedelta(days=28)).strftime('%m/%d/%Y')
    df.at[index, 'action'] = 'sent'

    # Edit CSV file
    df.to_csv('exhibitorlist.csv', index=False)
    print(df)

    Continue reading...

Compartilhe esta Página