How can I send multiple attachments to one email given this dataframe? I have only managed to send one file per mail, but I would like to attach several files in the same mail for one recipient.
My code where I send the email:
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()
CodePudding user response:
You can attach multiple attachments as several parts:
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)