0

I can't get this to attach multiple documents to an email. It attaches the first document and then sends the document. I am a noob when it comes to using the auto-email 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()
Aaron Cloud
  • 315
  • 4
  • 15

1 Answers1

1

Try this (Reference:- 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()
iamhimanshu0
  • 369
  • 2
  • 10
  • use `isinstance` to check the type of something, but really it's unpythonic to check types. Just trust users of your function to know to pass the right thing, that lets them pass things that work like lists that you never thought of without having to convert it for you. – Boris Verkhovskiy May 22 '21 at 04:30