В принципе, таким способом можно приложить любой файл, в котором хранится не текстовая информация.
Ниже пример скрипта, отсылающего .xlsx файл:
import smtplib
from email.utils import formatdate
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
dst_emails = 'recipient1@example.com, recipient2@example.com'
xlsxfile = '/home/user/project1/example.xlsx'
# E-mail block
me = "sender@example.com"
# Filling e-mail info
msg = MIMEMultipart()
msg['Subject'] = "Xlsx file"
msg['From'] = me
msg['To'] = dst_emails
to = msg['To'].split()
msg['Date'] = formatdate(localtime=True)
html = """\
<html>
<head></head>
<body>
<p><br>
<strong>This is a test e-mail</strong><br>
<br>
Place body text here
Best regards,<br>
Example user<br>
</p>
</body>
</html>
"""
# Record the MIME type
letter = MIMEText(html, 'html')
# Attach letter into message container.
msg.attach(letter)
# Attach xlsx file
part = MIMEBase('application', "octet-stream")
part.set_payload(open(xlsxfile, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'%(xlsxfile))
msg.attach(part)
# Send the message via example.com SMTP server.
s = smtplib.SMTP('mail.example.com')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, to, msg.as_string())
s.quit()
Ссылки:
- https://stackoverflow.com/questions/25346001/add-excel-file-attachment-when-sending-python-email