Advertisement
Guest User

Untitled

a guest
Mar 8th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. from email.message import EmailMessage
  2. import smtplib
  3. from pathlib import Path
  4.  
  5.  
  6. def send_simple_message(email, subject, html, from_subject="Github", bcc="", attachment=None):
  7. from_address = 'no-reply@someone.com'
  8. auth_user = 'SDSDFSDFSDFSDFSDF'
  9. auth_password = 'SDGDFGyyrtyrtyrtytrtyrtyrtyrt'
  10. smtp_host = 'email-smtp.eu-west-1.amazonaws.com'
  11. smtp_port = 587
  12.  
  13. def attach_file(email, filepath, extention, filename):
  14. types = {
  15. 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  16. 'pdf': 'application/pdf',
  17. # Put any mimetypes there
  18. }
  19. maintype, subtype = types[extention].split('/', 1)
  20. with open(filepath, 'rb') as content_file:
  21. content = content_file.read()
  22. email.add_attachment(content, maintype=maintype, subtype=subtype, filename=filename)
  23. return email
  24.  
  25. def create_email_message(from_address, to_address, subject, body, bcc):
  26. msg = EmailMessage()
  27. msg['From'] = "%s <%s>" % (from_subject, from_address)
  28. msg['To'] = to_address
  29. msg['Subject'] = subject
  30. msg['Bcc'] = bcc
  31. msg.set_content(body, subtype='html')
  32. return msg
  33.  
  34. msg = create_email_message(from_address, email, subject, html, bcc)
  35. if attachment:
  36. msg.make_mixed()
  37. filename = Path(attachment).name # file name ("report.pdf")
  38. subtype = str(Path(filename).suffix).replace('.', '') # "pdf"|"docx"|...file extention
  39. msg = attach_file(msg, attachment, subtype, filename)
  40.  
  41. with smtplib.SMTP(smtp_host, port=smtp_port) as smtp_server:
  42. smtp_server.ehlo()
  43. smtp_server.starttls()
  44. smtp_server.login(auth_user, auth_password)
  45. smtp_server.send_message(msg)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement