简体   繁体   English

如何使用 Python 循环发送多封带有附件的电子邮件

[英]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

在此处输入图像描述

VERY IMPORTANT:很重要:

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:为此,您需要:

  1. Open up Google Account (after your sign-in)打开Google 帐户(登录后)
  2. Under the "Signing in to Google" section, activate the "2-Step Verification""Signing in to Google"部分下,激活"2-Step Verification"
  3. Create an app password (to get a sixteen string characters)创建应用密码(获取十六个字符串字符)

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 python 发送带有多个附件的电子邮件 - How to use python to send emails with multiple attachments 使用 Python Dict 发送带有特定附件的电子邮件 - Using Python Dict to Send Emails with Specific Attachments Python发送带有相应附件的电子邮件 - Python send emails with corresponding attachments 使用循环向 Python 中的多个收件人发送自定义电子邮件 - Using a loop to send customized emails to multiple recipients in Python 如何在不使用Python触及附件的情况下有效地解析电子邮件 - How to efficiently parse emails without touching attachments using Python 使用python在Outlook电子邮件中保存附件 - Saving attachments in Outlook emails using python 使用 python 3 和 Gmail API 发送带有附件的电子邮件,我最终遇到文件损坏或 ConnectionAbortedError - Using python 3 and Gmail API to send emails with attachments, I end up with either corrupted files or ConnectionAbortedError 如何使用Mailgun发送包含多个附件和自定义文件名的邮件(来自Python) - How to send a mail with multiple attachments and custom file names using Mailgun (from Python) 如何在 Airflow 中使用 EmailOperator 发送多封邮件 - How to send multiple emails using EmailOperator in Airflow 如何从使用 Python 作为附件发送的电子邮件中下载附件? - How can I download attachments from emails sent as attachments with Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM