send mail with attachments


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import smtplib
  2. from email.MIMEMultipart import MIMEMultipart
  3. from email.MIMEBase import MIMEBase
  4. from email.MIMEText import MIMEText
  5. from email.Utils import COMMASPACE, formatdate
  6. from email import Encoders
  7. import os
  8.  
  9. def sendMail(to, subject, text, files=[],server="localhost"):
  10. assert type(to)==list
  11. assert type(files)==list
  12. fro = "Expediteur <[email protected]>"
  13.  
  14. msg = MIMEMultipart()
  15. msg['From'] = fro
  16. msg['To'] = COMMASPACE.join(to)
  17. msg['Date'] = formatdate(localtime=True)
  18. msg['Subject'] = subject
  19.  
  20. msg.attach( MIMEText(text) )
  21.  
  22. for file in files:
  23. part = MIMEBase('application', "octet-stream")
  24. part.set_payload( open(file,"rb").read() )
  25. Encoders.encode_base64(part)
  26. part.add_header('Content-Disposition', 'attachment; filename="%s"'
  27. % os.path.basename(file))
  28. msg.attach(part)
  29.  
  30. smtp = smtplib.SMTP(server)
  31. smtp.sendmail(fro, to, msg.as_string() )
  32. smtp.close()
  33.  
  34.  
  35. sendMail(
  36. "hello","cheers",
  37. ["photo.jpg","memo.sxw"]
  38. )

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.