Application which monitors a folder and sends each file via mail
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import smtplib
  2. from pathlib import Path
  3. from email.mime.multipart import MIMEMultipart
  4. from email.mime.base import MIMEBase
  5. from email.mime.text import MIMEText
  6. from email.utils import COMMASPACE, formatdate
  7. from email import encoders
  8. def send_mail(send_from, send_to, subject, message, files=[],
  9. server="localhost", username='', password='',
  10. use_tls=True):
  11. """Compose and send email with provided info and attachments.
  12. Args:
  13. send_from (str): from name
  14. send_to (list[str]): to name(s)
  15. subject (str): message title
  16. message (str): message body
  17. files (list[str]): list of file paths to be attached to email
  18. server (str): mail server host name
  19. username (str): server auth username
  20. password (str): server auth password
  21. use_tls (bool): use TLS mode
  22. """
  23. msg = MIMEMultipart()
  24. msg['From'] = send_from
  25. msg['To'] = send_to
  26. msg['Date'] = formatdate(localtime=True)
  27. msg['Subject'] = subject
  28. msg.attach(MIMEText(message))
  29. for path in files:
  30. part = MIMEBase('application', "octet-stream")
  31. with open(path, 'rb') as file:
  32. part.set_payload(file.read())
  33. encoders.encode_base64(part)
  34. part.add_header('Content-Disposition',
  35. 'attachment; filename={}'.format(Path(path).name))
  36. msg.attach(part)
  37. smtp = smtplib.SMTP(server)
  38. if use_tls:
  39. smtp.starttls()
  40. smtp.login(username, password)
  41. smtp.sendmail(send_from, send_to.split(', '), msg.as_string())
  42. smtp.quit()