I am trying to send a csv file as an attachment via a simple function in python 3.6.
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def email():
msg = MIMEMultipart()
msg['Subject'] = 'test'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
msg.preamble = 'preamble'
with open("test.csv") as fp:
record = MIMEText(fp.read())
msg.attach(record)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("[email protected]", "password")
server.sendmail("[email protected]", "[email protected]", msg)
server.quit()
Calling email()
produces the error expected string or bytes-like object
. Redefining server.sendmail("[email protected]", "[email protected]", msg)
as server.sendmail("[email protected]", "[email protected]", msg.as_string())
causes an email to be sent, but sends the csv file in the body of the email, NOT as an attachment. can anyone give me some pointers on how to send the csv file as an attachment?
Content-Disposition
header to your attachment?msg.add_header('Content-Disposition', 'attachment', filename='test.csv')
'
onmsg['From'] = '[email protected]
?