[英]How to send multiple emails in a loop with attachments using Python
Hello, can anyone help me out to write a code which helps me to send multiple emails with attachments in loops at once?你好,谁能帮我写一个代码来帮助我一次发送多封带有附件的电子邮件?
Now I am explaining what I exactly want to achieve.现在我正在解释我到底想要实现什么。
This is my table available in excel sheet这是我在 excel 表中可用的表
enter image description here在此处输入图像描述
Step 01 - I have multiple excel report saved in folder with the same name as the Emp Number as mentioned in above table.步骤 01 - 我有多个 excel 报告保存在与上表中提到的Emp 编号同名的文件夹中。
Step 02 - so I want want code such as it will pick the report from folder by matching report name with the Emp Number mentioned in table and send mail to Email id which is available against those Emp Number步骤 02 - 所以我想要代码,例如它将通过将报告名称与表中提到的 Emp 编号匹配来从文件夹中选择报告,并将邮件发送到 Email id,该 ID 可用于这些 Emp 编号
note: report name and Emp Number both is same.注意:报告名称和员工编号均相同。
It is possible because right now I am sending more than 3210+ emails manually , which is exhausting me.这是可能的,因为现在我手动发送超过 3210 封电子邮件,这让我筋疲力尽。
Supposing the usage of Outlook
for Windows as application to send emails, and you have some table which you want to send called dataset
, and a list of emails called emails
:假设将
Outlook
用于 Windows 作为发送电子邮件的应用程序,并且您有一些要发送的名为dataset
的表和一个名为emails
的电子邮件列表:
Initialize the Outlook application, make sure that you have opened it alrealdy before starting the script:初始化 Outlook 应用程序,确保在启动脚本之前已经打开它:
import win32com.client as win32
olApp = win32.Dispatch("Outlook.Application")
olNS = olApp.GetNameSpace("MAPI")
email_sender = "your.email@xxx.xxx"
Creating an email object (empty):创建 email object(空):
mail_item = olApp.CreateItem(0)
Supposing you want to send a shared email to everyone in copy you can do:假设您想将共享 email 发送给副本中的每个人,您可以执行以下操作:
mail_item.To = "; ".join(emails)
Otherwise, if you want to email singularly just loop to email or use multithreading
which is more appropriate/fast rather than multiprocessing
for this kind of tasks.否则,如果您想单独使用 email,只需循环到 email 或使用更合适/更快的
multithreading
而不是multiprocessing
来处理此类任务。
mail_item.Subject = "An unusual email."
mail_item.BodyFormat = 1
mail_item._oleobj_.Invoke(*(64209, 0, 8, 0, olNS.Accounts.Item(email_sender)))
Then, initialize your body as a string:然后,将你的 body 初始化为一个字符串:
body = ""
Think about a static header which will describe the email and the content of the table and add it to the body:考虑一个 static header ,它将描述 email 和表格的内容并将其添加到正文中:
body += """<td style="line-height:15px;font-family:Arial;mso-line-height-rule:exactly;padding-bottom:5px">{}</td></br>""".format("A Random Header.")
Again, add to the body the pandas table with the .to_html()
to parse it correctly as html:再次,将带有
.to_html()
的 pandas 表添加到正文中,以将其正确解析为 html:
body += """<br><pre>{}</br></pre>""".format(dataset.to_html())
Give the body to the mail_item :将正文交给mail_item :
mail_item.HTMLBody = "<html><body>{}</html></body>".format(body)
Send the email:发送 email:
mail_item.Send()
Considering that you have a @gmail address, you can run the code below to send multiple emails with different ExcelFiles attachements (stored in one single folder) to different recipients (including non-gmail addresses).考虑到您有一个@gmail 地址,您可以运行下面的代码将具有不同 ExcelFiles 附件(存储在一个文件夹中)的多封电子邮件发送给不同的收件人(包括非 Gmail 地址)。
import pandas as pd
import smtplib
from email.message import EmailMessage
df = pd.read_excel(r'path\\to\\your\\emails_Excelfile.xlsx')
for index, row in df.iterrows():
emp_number = row['EMP Number']
email_id = row['Email ID']
msg = EmailMessage()
msg['Subject'] = 'Report number ' + str(emp_number)
msg['From'] = 'put_your_@gmail_here'
msg['To'] = email_id
msg.set_content("Put your message here")
with open(fr"path\\to\\reportsFolder\{emp_number}.xlsx", 'rb') as f:
file_data=f.read()
file_name=f.name
msg.add_attachment(file_data, maintype='application', subtype='xlsx', filename=file_name)
try:
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
server.login('put_your_@gmail_here', 'put_your_AppPassword_here')
server.send_message(msg)
except:
pass
>>> Result
Since the "Access for the less secure app" in Gmail has been deactivated by Google, you have to generate an APP password so smtplib
can login your gmail.由于 Gmail 中的“访问不太安全的应用程序”已被 Google 停用,您必须生成一个 APP 密码,以便
smtplib
可以登录您的 gmail。 And to do this, you need to:为此,您需要:
"Signing in to Google"
section, activate the "2-Step Verification"
"Signing in to Google"
部分下,激活"2-Step Verification"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.