smtplib - Email using Python with Excel attachment -
#!/usr/bin/env python3 import smtplib,email,email.encoders,email.mime.text,email.mime.base email.mime.multipart import mimemultipart email.mime.text import mimetext email import encoders email.message import message email.mime.audio import mimeaudio email.mime.base import mimebase email.mime.image import mimeimage email.mime.multipart import mimemultipart email.mime.text import mimetext msg = mimemultipart() # me == email address # == recipient's email address me = "sender@email.com" = "reciever@email.com " # create message container - correct mime type multipart/alternative. msg = mimemultipart('mixed') msg['subject'] = "msg" msg['from'] = me msg['to'] = # create body of message (a plain-text , html version). text = "hi\nthis text-only" html = """\ <html> email</html> """ part1 = mimetext(text, 'plain') part2 = mimetext(html, 'html') #attach excel file: fp = open('teststatus.xlsx', 'rb') file1=email.mime.base.mimebase('application','vnd.ms-excel') file1.set_payload(fp.read()) fp.close() email.encoders.encode_base64(file1) file1.add_header('content-disposition','attachment;filename=anexcelfile.xlsx') # attach parts message container. # according rfc 2046, last part of multipart message, in case # html message, best , preferred. msg.attach(part2) msg.attach(part1) msg.attach(file1) composed = msg.as_string() fp = open('msgtest.eml', 'w') fp.write(composed) # credentials (if needed) # actual mail send server = smtplib.smtp('dc1smtp.com') server.starttls() server.sendmail(me, you, msg) server.quit() fp.close() when running it, see error message. traceback (most recent call last): file "excel.py", line 57, in <module> server.sendmail(me, you, msg) file "c:\python33\lib\smtplib.py", line 775, in sendmail (code, resp) = self.data(msg) file "c:\python33\lib\smtplib.py", line 516, in data q = _quote_periods(msg) file "c:\python33\lib\smtplib.py", line 167, in _quote_periods return re.sub(br'(?m)^\.', b'..', bindata) file "c:\python33\lib\re.py", line 170, in sub return _compile(pattern, flags).sub(repl, string, count) typeerror: expected string or buffer
i have tested code , working. problem having that, when run it, dont recieve emails testing with. when run code. creates file named "msgtest.eml". file draft of email or something. can show me how use show , email instead of draft?
import smtplib me = "me@me.com" = "you@you.com" # insert code here msg = ... s = smtplib.smtp('localhost') s.sendmail(me, [to], msg.as_string())
Comments
Post a Comment