[英]How to send multiple emails in a loop with attachments using Python
你好,誰能幫我寫一個代碼來幫助我一次發送多封帶有附件的電子郵件?
現在我正在解釋我到底想要實現什么。
這是我在 excel 表中可用的表
步驟 01 - 我有多個 excel 報告保存在與上表中提到的Emp 編號同名的文件夾中。
步驟 02 - 所以我想要代碼,例如它將通過將報告名稱與表中提到的 Emp 編號匹配來從文件夾中選擇報告,並將郵件發送到 Email id,該 ID 可用於這些 Emp 編號
注意:報告名稱和員工編號均相同。
這是可能的,因為現在我手動發送超過 3210 封電子郵件,這讓我筋疲力盡。
假設將Outlook
用於 Windows 作為發送電子郵件的應用程序,並且您有一些要發送的名為dataset
的表和一個名為emails
的電子郵件列表:
初始化 Outlook 應用程序,確保在啟動腳本之前已經打開它:
import win32com.client as win32
olApp = win32.Dispatch("Outlook.Application")
olNS = olApp.GetNameSpace("MAPI")
email_sender = "your.email@xxx.xxx"
創建 email object(空):
mail_item = olApp.CreateItem(0)
假設您想將共享 email 發送給副本中的每個人,您可以執行以下操作:
mail_item.To = "; ".join(emails)
否則,如果您想單獨使用 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)))
然后,將你的 body 初始化為一個字符串:
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.")
再次,將帶有.to_html()
的 pandas 表添加到正文中,以將其正確解析為 html:
body += """<br><pre>{}</br></pre>""".format(dataset.to_html())
將正文交給mail_item :
mail_item.HTMLBody = "<html><body>{}</html></body>".format(body)
發送 email:
mail_item.Send()
考慮到您有一個@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
由於 Gmail 中的“訪問不太安全的應用程序”已被 Google 停用,您必須生成一個 APP 密碼,以便smtplib
可以登錄您的 gmail。 為此,您需要:
"Signing in to Google"
部分下,激活"2-Step Verification"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.