add excel file attachment when sending python email
This is the code that worked for me- to send an email with an attachment in python
#!/usr/bin/python
import smtplib,ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
def send_mail(send_from,send_to,subject,text,files,server,port,username='',password='',isTls=True):
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
part = MIMEBase('application', "octet-stream")
part.set_payload(open("WorkBook3.xlsx", "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="WorkBook3.xlsx"')
msg.attach(part)
#context = ssl.SSLContext(ssl.PROTOCOL_SSLv3)
#SSL connection only working on Python 3+
smtp = smtplib.SMTP(server, port)
if isTls:
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
Sending xlsx file using SMTP & Python 3
Just for the record:
xlsx.add_header('Content-Dispolsition', 'attachment', filename=filename)
should be
xlsx.add_header('Content-Disposition', 'attachment', filename=filename)
Related Topics
How to Correct Typeerror: Unicode-Objects Must Be Encoded Before Hashing
Python Super :Typeerror: _Init_() Takes 2 Positional Arguments But 3 Were Given
Numpy Distance Calculations of Different Shaped Arrays
Stripping Non Printable Characters from a String in Python
How to Extract Address from Raw Text Using Nltk in Python
Getting the Bounding Box of the Recognized Words Using Python-Tesseract
Unable Log in to the Django Admin Page With a Valid Username and Password
Webscraping Financial Data from Morningstar
Pyqt: Getting Widgets to Resize Automatically in a Qdialog
How to Set Proxy Authentication (User & Password) Using Python + Selenium
Print a List of Space-Separated Elements
Pandas: Calculate the Percentage Between Two Rows and Add the Value as a Column
Find All CSV Files in a Directory Using Python
How to Pass a .Txt File to a Function in Python