I'm trying to attach an xlsx file to my email. I looked up solutions and it involves using email.encoders. But when I use this solution I get an error. I'm using a solution that someone else has working.
File "C:\Documents and Settings\Desktop\AppTera\dev\MTC_test\MTC_sender.py", line 41, in sendmail
s.sendmail(FROMADDR, TOADDR, message.as_string())
AttributeError: 'list' object has no attribute 'encode'
def sendmail():
SERVER = 'server.com'
FROMADDR = "joe@example.com"
TOADDR = ['bob@example.com']
CCADDR = ['bill@example.com']
message = MIMEMultipart('mixed')
message['From'] = FROMADDR
message['To'] = TOADDR
message['Subject'] = "Reporting for IVR Application"
BODY = "Hello Angela,\n\nI'm attaching the reports for %s/%s. These are the same reports\
you have requested in the past.\n\nPlease let me know if you need any additional reports.\n\n\
Thank you"% (str(MONTH), str(YEAR))
message.attach(MIMEText(BODY, 'plain'))
filename = "results.csv.xlsx"
path = r'C:\Documents and Settings\Desktop\MonthlyReports\MTC\%s_%s' % (str(YEAR), str(MONTH))
os.chdir(path)
fileMsg = MIMEBase('application', 'xlsx')
fileMsg.set_payload(open('results.csv.xlsx', 'rb').read())
encoders.encode_base64(fileMsg)
fileMsg.add_header('Content-Disposition','attachment;filename=results.csv.xls')
message.attach(fileMsg)
s = smtplib.SMTP(SERVER, 25)
s.set_debuglevel(1)
s.sendmail(FROMADDR, TOADDR, message.as_string())
s.quit()
Is there another way that I can send an attached file along with a body message?
s
is a SMTP object which you created by s = smtplib.SMTP(SERVER, 25)
. So the parameters for s.sendmail(FROMADDR, TOADDR, message.as_string())
should be according to the documentation.
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])
Send mail. The required arguments are an RFC 822 from-address string, a list of RFC 822 to-address strings (a bare string will be treated as a list with 1 address), and a message string. The caller may pass a list of ESMTP options (such as 8bitmime) to be used in MAIL FROM commands as mail_options. ESMTP options (such as DSN commands) that should be used with all RCPT commands can be passed as rcpt_options. (If you need to use different ESMTP options to different recipients you have to use the low-level methods such as mail(), rcpt() and data() to send the message.)
Make sure FROMADDR is a string(not a list), TOADDR should be a string or a list of strings(which are RFC 822 email format strings).