0
votes

Hi I'm new to learning python and I'm trying to send emails to a few hundred different recipients with a different attachment to each of them. I have the recipients data in a database and a folder with all the files in it.

Database has supplier id, name and email

Database example

The folder structure is just one folder with all the files in it for example :

Folder screenshot

Supplier files folder --

123.xls

123.pdf

456.xls

789.pdf

any direction on how to get started with this is appreciated. Thank you

1
first try and map each of the supplier and the email.. have it as a dict maybe.. and follow the above to send an emailYatish Kadam

1 Answers

0
votes

In this example I will use an answer that I gave to another question (How do I attach separate PDF's to contact list email addresses using Python?) , I use a csv file that contains the addresses and the file path that corresponds to it like img bellow :

users.csv :

enter image description here

folder with csv files :

enter image description here

And this is the code:

import smtplib, ssl
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

# read the file containing the database with the mail and the corresponding file
e = pd.read_csv("users.csv")
# In this example we will use gmail 
context = ssl.create_default_context()
server = smtplib.SMTP_SSL('smtp.gmail.com', 465,context=context)
server.login('[email protected]','mypass')

body = ("""
Hi there

Test message

Thankyou
""")
subject = "Send emails with attachment"
fromaddr='[email protected]'

for index, row in e.iterrows():
    print (row["Emails"]+row["csv"])
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain'))
    filename = row["csv"]
    toaddr = row["Emails"]
    attachment = open(row["csv"], "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)

print("Emails sent successfully")

server.quit()

if you use a gmail account, check that you have it permissions to send emails from other types of clients (https://support.google.com/accounts/answer/6010255)