【问题标题】:Sending mails with multiple attachment in Python在 Python 中发送带有多个附件的邮件
【发布时间】:2020-08-28 10:26:45
【问题描述】:

我编写了一个代码来使用 Python 向多个用户发送带有附件的邮件。因此,代码将访问 csv 文件,获取电子邮件地址和相应的 excel 文件并发送带有附件的邮件。

此代码运行良好,但要求已更改。新要求是,我需要将多个文件附加到一个收件人(不能发送多封邮件)。例如,我需要附上 TEST.pdf 和另一个 TEST123.pdf 文件并发送到 test1@hotmail.com(请参考图片)。

我已尽力而为,但代码中不断出现错误。有人可以帮我解决这个问题吗?

我的 Python 代码

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import pandas as pd

e = pd.read_csv("C:\\Users\\Hp-Pc\\Desktop\\mail.csv")
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)

server.login("email", "pw")

body = ("""
Hi There

Please refer attachment

Thanks & Regards
""")
subject = ["PDF"]
fromaddr='email'

for index, row in e.iterrows():
print (row["Emails"]+row["PDF"])
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['Subject'] = row["PDF"]
msg.attach(MIMEText(body, 'plain'))
filename = row["PDF"]
toaddr = row["Emails"]
attachment = open(row["PDF"], "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()

【问题讨论】:

    标签: python email


    【解决方案1】:

    您可以使用AutoMailer应用程序(用Python制作,作者:我自己)

    它可以发送多个附件。它从 CSV 文件中读取收件人

    (不用担心,您可以轻松地将 Excel 文件导出为 CSV,Google Sheets 和 Microsoft Excel,Libre Office 都支持导出为 CSV 格式)

    https://github.com/aahnik/AutoMailer

    这是开源的,您可以看到该功能是如何实现的。访问上面的链接

    【讨论】:

      【解决方案2】:

      请看下文。

      from importlib import reload
      import win32com.client as win32
      import pythoncom
      import sys
      import os
      import pandas as pd
      
      reload(sys)
      
      pythoncom.CoInitialize()
      outlook = win32.Dispatch('outlook.application')
      
      def sendmail(receiver, attachment, subject):
          receiver = receiver
          attachment = attachment
          sub = subject
          body = "Please find the attached supporting documents for member rebates."
          mail = outlook.CreateItem(0)
          mail.To = receiver
          mail.subject = sub.encode('utf-8').decode('utf-8')
          mail.Body = body.encode('utf-8').decode('utf-8')
      # Upload multiple attachments/files that meet the conditions/requirements
          for i in range(len(attachment)):
              mail.Attachments.Add(attachment[i])
          mail.Send()
      
      # Folder of attachments
      path = r"C:\Users\Desktop "
      
      # Address spreadsheet
      addr = pd.read_excel(r"C:\Users\Desktop\address.xlsx")
      
      for j in range(len(addr.Code)):
          dirlist = []
      # Address spreadsheet includes “Code” which is the recipient’s name/ID, and “add”, the email address
          sub_code = addr.Code[j].astype("str")
          subjects = sub_code + " - invoices"
      # If the file names include the recipient’s ID at the start of 4 letters, the file(s) would be added to the list
          for dirpath,dirname,filename in os.walk(path):
              print(addr.Code[j].astype("str"))
              for i in filename:
                  if i[0:4] == sub_code:
                      dirlist.append(os.path.join(dirpath,i))
          # Send emails to multiple recipients with corresponding attachments            
          sendmail(add r["add"][j], dirlist, subjects)
      
      

      我使用它向每个收件人发送多张发票。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-30
        • 2018-03-09
        • 1970-01-01
        • 2014-09-25
        • 2019-05-25
        • 2021-09-14
        • 2014-11-09
        • 2017-02-04
        相关资源
        最近更新 更多