![](/img/trans.png)
[英]Python script to send email to multiple recipients with different attachments
[英]Sending Email to different recipients with different file attachments using python
在这个例子中,我将使用我对另一个问题的回答( 如何使用 Python 将单独的 PDF 附加到联系人列表电子邮件地址? ),我使用一个 csv 文件,其中包含地址和对应的文件路径,如 img波纹管:
用户.csv:
包含 csv 文件的文件夹:
这是代码:
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('mymail@gmail.com','mypass')
body = ("""
Hi there
Test message
Thankyou
""")
subject = "Send emails with attachment"
fromaddr='mymail@gmail.com'
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()
如果您使用 Gmail 帐户,请检查您是否有权从其他类型的客户端发送电子邮件 ( https://support.google.com/accounts/answer/6010255 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.