如何根据用户及其要附加的文件添加多个附件?

How do I add multiple attachments depending of the user and their files to attach?

给定此数据框,如何将多个附件发送到一封电子邮件?我每封邮件只能发送一个文件,但我想在同一封邮件中为一个收件人附加多个文件。

我的数据框看起来像:

我发送电子邮件的代码:

def enviar_mail(from, to, file_name, link, title):

  from email.mime.multipart import MIMEMultipart
  from email.mime.base import MIMEBase
  from email.mime.text import MIMEText
  from email.mime.image import MIMEImage
  import smtplib
  from email import encoders
  from google.colab import files
  from email.utils import formataddr
  import email.utils
  import time
  from datetime import date

  msg = MIMEMultipart('alternative')
  msg['From'] =email.utils.formataddr(( "Mail",from))
  msg['To'] = to
  msg['Subject'] = 'Subject'

  bodytext=f"BODY OF THE EMAIL IN HTML"
  body=f"""\
          <html>
              <body>
                <p style="color:black;"> {bodytext}
                </p>
              </body>
          </html>
"""


  msg.attach(MIMEText(body, 'html'))

  attachment = open(file_name, 'rb')
  part = MIMEBase('application', "octet-stream")
  part.set_payload((attachment).read())
  encoders.encode_base64(part)
  part.add_header('Content-Disposition', "attachment; filename= %s" % file_name)
  msg.attach(part)
  
  mailserver = smtplib.SMTP('smtp.office365.com',587)
  mailserver.ehlo()
  mailserver.starttls()
  mailserver.login(from, 'mypassword')

  mailserver.send_message(msg, rcpt_options=['NOTIFY=SUCCESS,DELAY,FAILURE'])
  mailserver.quit()

您可以将多个附件作为几个部分附加:

attachment1 = open(file_1, 'rb')
part = MIMEBase('application', "octet-stream")
part.set_payload(attachment1.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % file_1)
msg.attach(part)


attachment2 = open(file_2, 'rb')
part = MIMEBase('application', "octet-stream")
part.set_payload(attachment2.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % file_2)
msg.attach(part)