Skip to content Skip to sidebar Skip to footer

How Do I Attach Separate Pdf's To Contact List Email Addresses Using Python?

I have written a script that sends individual emails to all contacts in an Excel table. The table looks like this: Names Emails PDF Name1 Email1@email.com PDF1.pdf N

Solution 1:

I made a little changes , and make you sure the pdf field has the pdf path Edit:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from string import Template
import pandas as pd

#e = pd.read_csv("Contacts.csv")
e = pd.read_excel("Contacts.xlsx")
server = smtplib.SMTP(host='smtp.outlook.com', port=587)
server.starttls()
server.login('yourmail@mail.com','yourpass')

body = ("""
Hi there

Test message

Thankyou
""")
subject = "Send emails with attachment"
fromaddr='yourmail@mail.com'
#body = "Subject: {}\n\n{}".format(subject,msg)
#Emails,PDF
for index, row in e.iterrows():
    print (row["Emails"]+row["PDF"])
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
    filename = row["PDF"]
    toaddr = row["Emails"]
    attachment = open(row["PDF"], "rb")
    part = MIMEBase('application', 'octet-stream')
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
    msg.attach(part)
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)
    #server.sendmail('sender_email',emails,body)

print("Emails sent successfully")

server.quit()

Post a Comment for "How Do I Attach Separate Pdf's To Contact List Email Addresses Using Python?"