有没有办法在 Python 的 Pandas 数据框中通过 SMTPLib 将电子邮件连接到多个收件人? [复制]
Posted
技术标签:
【中文标题】有没有办法在 Python 的 Pandas 数据框中通过 SMTPLib 将电子邮件连接到多个收件人? [复制]【英文标题】:Is there a way of concatenating emails to multiple recipients via SMTPLib in a Pandas dataframe in Python? [duplicate] 【发布时间】:2021-07-26 08:07:02 【问题描述】:我有下面的代码来发送特定于熊猫数据框中某些地址的电子邮件。类型为 pandas.series。我怎样才能发送具有多个地址的每个列表?有些有多达 8 个电子邮件地址,用分号 (;) 分隔。发送出去的唯一可能性是到一个地址。从下面的数据框中,我可以将特定于 ID 的电子邮件发送到 TestEmail 值。没有任何东西适用于电子邮件。我收到以下错误:
SMTPRecipientsRefused: '': (421, b'4.7.0 Too many protocol errors (6) on this connection, closing transmission channel.')
数据框 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
代码如下。对于单个地址,我可以将名称与 df['IDs'] 值匹配的附件发送到相应的电子邮件地址。
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()
【问题讨论】:
【参考方案1】:取自这个答案:How to send email to multiple recipients using python smtplib?
这是您必须更改的行:
首先将 email_to 拆分为不同电子邮件的列表,然后使用 ", " 加入
msg['To'] = ", ".join(email_to.split(";"))
【讨论】:
以上是关于有没有办法在 Python 的 Pandas 数据框中通过 SMTPLib 将电子邮件连接到多个收件人? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
python 一个将pandas数据帧转换为JSON对象的小脚本。有没有更好的办法?
Python Pandas:有没有办法根据列表中的字符串获取子集数据帧