Guest User

Untitled

a guest
May 20th, 2018
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  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. import time
  9. import random
  10.  
  11. def generate_message_id(msg_from):
  12. domain = msg_from.split("@")[1]
  13. r = "%s.%s" % (time.time(), random.randint(0, 100))
  14. mid = "<%s@%s>" % (r, domain)
  15. return mid
  16.  
  17. def send_mail(msg_from, to, subject, text,
  18. files=[],server="localhost", debug=False):
  19. assert type(to)==list
  20. assert type(files)==list
  21.  
  22. msg = MIMEMultipart()
  23. msg['From'] = msg_from
  24. msg['To'] = COMMASPACE.join(to)
  25. msg['Date'] = formatdate(localtime=True)
  26. msg['Subject'] = subject
  27.  
  28. text = text.encode("utf-8")
  29. text = MIMEText(text, 'plain', "utf-8")
  30. msg.attach(text)
  31.  
  32. msg.add_header('Message-ID', generate_message_id(msg_from))
  33.  
  34. for file in files:
  35. part = MIMEBase('application', "octet-stream")
  36. part.set_payload( open(file,"rb").read() )
  37. Encoders.encode_base64(part)
  38. part.add_header('Content-Disposition', 'attachment; filename="%s"'
  39. % os.path.basename(file))
  40. msg.attach(part)
  41.  
  42. if not debug:
  43. smtp = smtplib.SMTP(server)
  44. smtp.sendmail(msg_from, to, msg.as_string())
  45. smtp.close()
  46.  
  47. return msg
  48.  
  49. #sendMail(["destination@dest.kio"], "hello","cheers", ["photo.jpg","memo.sxw"])
Add Comment
Please, Sign In to add comment