I have the below code to send out emails specific to certain addresses all in a pandas dataframe. The type says pandas.series. How can I be able to send each list with multiple addresses? Some have upto 8 email addresses separated by a semi-colon(;). Only possibility of sending out is to a single address. From the below dataframe, I'm able to send emails specific to the IDs to TestEmail values. Nothing works for Emails. I get the below error :
SMTPRecipientsRefused: {'': (421, b'4.7.0 Too many protocol errors (6) on this connection, closing transmission channel.')}
Dataframe df
IDs CompanyNames Emails TestEmail
2003 XXX xx@gmail.com;yy@ryt.com;dd@xx.com;ii@dd.com kk@kk.com
2004 XXXYY xx@gmail.com;yy@ryt.com;dd@xx.com kk@kk.com
2005 XXTTNN xx@gmail.com;yy@ryt.com;dd@xx.com;ii@dd.com kk@kk.com
2006 BBOOLL xx@gmail.com;yy@ryt.com kk@kk.com
The code is below. To the single address, I'm able to send attachments with names matching df['IDs'] values to the corresponding email address.
import smtplib, ssl
from email.message import EmailMessage
import getpass
ids = df['IDs']
emails_to = df['Emails'] #Pandas column with email addresses split by semi-colon(;)
namesofcompanies = df["CompanyNames"]
sendfrom = df["SenderList"]
date_7days = (datetime.now() + timedelta(days=7)).strftime('%d/%m/%Y')
date_14days = (datetime.now() + timedelta(days=13)).strftime('%d/%m/%Y')
email_pass = input() #Office 365 password
context=ssl.create_default_context()
for i in range(len(emails_to)): # iterate through the records
# for every record get the name and the email addresses
ID = str(ids[i])
Emaitstosendto = emails_to[i]
companynames = namesofcompanies[i]
tosendfrom = sendfrom[i]
if my_files_dict.get(ID): #Looks for attachments in the same folder with same name as the corresponding record
smtp_ssl_host = 'smtp.office365.com'
smtp_ssl_port = 587
email_login = "xxx@xxx.com" #Office 365 email
email_from = tosendfrom
email_to = Emaitstosendto
msg = MIMEMultipart()
msg['Subject'] = "Received Emails between "+date_7days+" - "+date_14days
msg['From'] = email_from
msg['To'] = email_to
msg['X-Priority'] = '2'
text = ("XXXX,\n"
f"xxxxxx\n\n")
msg.attach(MIMEText(text))
filename = my_files_dict.get(ID)#Files in the folder matching the ID
fo = open(filename,'rb')
s2 = smtplib.SMTP(smtp_ssl_host, smtp_ssl_port)
s2.starttls(context=context)
s2.login(email_login, email_pass)
attachment = email.mime.application.MIMEApplication(fo.read(),_subtype="xlsx")
fo.close()
attachment.add_header('Content-Disposition','attachment',filename=filename)
msg.attach(attachment)
s2.send_message(msg)
s2.quit()
Taken from this answer: How to send email to multiple recipients using python smtplib?
This is the line you have to change:
First split the email_to into a list of different emails and then join using ", "
msg['To'] = ", ".join(email_to.split(";"))