MIMEMultipart, MIMEText, MIMEBase, and payloads for sending email with file attachment in Python -
without prior knowledge of mime, tried learned how write python script send email file attachment. after cross-referencing python documentation, stack overflow questions, , general web searching, settled following code [1] , tested working.
import smtplib email.mimemultipart import mimemultipart email.mimetext import mimetext email.mimebase import mimebase email import encoders fromaddr = "your email" toaddr = "email address send to" msg = mimemultipart() msg['from'] = fromaddr msg['to'] = toaddr msg['subject'] = "subject of email" body = "text want send" msg.attach(mimetext(body, 'plain')) filename = "name of file extension" attachment = open("path of file", "rb") part = mimebase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('content-disposition', "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.smtp('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, "your password") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit()
i have rough idea of how script works now, , worked out following workflow. please let me know how accurate flowchart(?) is.
as.string() | +------------mimemultipart | |---content-type | +---header---+---content disposition +----.attach()-----+----mimebase----| | +---payload (to encoded in base64) +----mimetext
how know when use mimemultipart, mimetext , mimebase? seems complicated question, maybe offer general rules-of-thumb me?
- i read mime has tree-like structure[2] , mean mimemultipart @ top?
- in first code block, mimemultipart encodes ['from'], ['to'], , ['subject'], in python documentation, mimetext can used encode ['from'], ['to'], , ['subject']. how decide 1 use?
- what "payload"? content transported? if so, kind of content include (i noticed body text , attachment treated payloads)? thought easy question not find satisfying, reliable, , simple answer.
- is true although mime can attach file formats simpler texts, @ end encoding, header information, , payloads turned strings can passed .sendmail()?
[1]http://naelshiab.com/tutorial-send-email-python/
[2]http://blog.magiksys.net/generate-and-send-mail-with-python-tutorial
Comments
Post a Comment