简体   繁体   English

如何使用 python 发送带有多个附件的电子邮件

[英]How to use python to send emails with multiple attachments

I can't get this to attach multiple documents to an email.我无法将多个文档附加到 email。 It attaches the first document and then sends the document.它附加第一个文档,然后发送该文档。 I am a noob when it comes to using the auto-email function.在使用自动电子邮件 function 时,我是个菜鸟。 Could anyone explain this or show me how to fix this?谁能解释一下或告诉我如何解决这个问题?

    self.name = name
    fromaddr = "Your Email"
    toaddr = "Sending Email"
    msg = MIMEMultipart()
    #email address
    msg['From'] = fromaddr
    # Receivers email address
    msg['To'] = toaddr
    #subject
    msg['Subject'] = ' Weekly Report'
    #body of the mail
    body = 'Hey, I\'m testing the automated email function, let me know if you get it and how does it look!'
    #msg instance
    msg.attach(MIMEText(body, 'plain'))
    # open the file to be sent
    a = 0
    for i in self.name:
        while a < len(self.name):
            filename = i + '.pdf'
            attachment = open(i + '.pdf', "rb")
            a+=1
            print(len(self.name))
            print(a)
    p = MIMEBase('application', 'octet-stream')
    p.set_payload((attachment).read())
    encoders.encode_base64(p)
    p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
    msg.attach(p)
    s = smtplib.SMTP('smtp.gmail.com', 587)
    s.starttls()
    s.login(fromaddr, "password")
    text = msg.as_string()
    s.sendmail(fromaddr, toaddr, text)
    s.quit()

Try this (Reference:- https://dzone.com/articles/send-email-attachments-python )试试这个(参考:- https://dzone.com/articles/send-email-attachments-python

import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
  assert type(send_to)==list
  assert type(files)==list

  msg = MIMEMultipart()
  msg['From'] = send_from
  msg['To'] = COMMASPACE.join(send_to)
  msg['Date'] = formatdate(localtime=True)
  msg['Subject'] = subject

  msg.attach( MIMEText(text) )

  for f in files:
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(file,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
    msg.attach(part)

  smtp = smtplib.SMTP(server)
  smtp.sendmail(send_from, send_to, msg.as_string())
  smtp.close()

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM