Advertisement
Guest User

Untitled

a guest
Jun 1st, 2017
507
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. import os
  4. import json
  5. import logging
  6. import smtplib
  7. from email.mime.multipart import MIMEMultipart
  8. from email.mime.text import MIMEText
  9.  
  10. logger = logging.getLogger(__name__)
  11.  
  12. config_file = './smtp.gmail.conf'
  13. conf = {}
  14.  
  15. """ Configuration file example :
  16. {
  17. "gmail_host": "smtp.gmail.com",
  18. "gmail_port": 587,
  19. "gmail_user": "user@gmail.com",
  20. "gmail_pwd": "password"
  21. }
  22. """
  23.  
  24.  
  25. def load_conf():
  26. global conf
  27. if os.path.exists(config_file) and os.path.isfile(config_file):
  28. with open(config_file, mode='r', encoding='UTF-8') as file:
  29. conf = json.load(file)
  30. else:
  31. logger.error('Can not found GMAIL SMTP configuration file : ' + config_file)
  32. raise FileNotFoundError
  33. if not {'gmail_host', 'gmail_port', 'gmail_user', 'gmail_pwd'} <= conf.keys():
  34. logger.error('Invalid GMAIL SMTP configuration in : ' + config_file)
  35. raise ValueError
  36. load_conf()
  37.  
  38.  
  39. def send_multiple_mail(to: list, subject: str = '', text: str = '', html: str = ''):
  40. smtpserver = smtplib.SMTP(conf['gmail_host'], conf['gmail_port'])
  41. smtpserver.ehlo()
  42. smtpserver.starttls()
  43. smtpserver.login(conf['gmail_user'], conf['gmail_pwd'])
  44. # construct mail
  45. msg = MIMEMultipart('alternative')
  46. msg['Subject'] = subject
  47. msg['From'] = conf['gmail_user']
  48. msg['To'] = ", ".join(to)
  49. if text or not html:
  50. msg.attach(MIMEText(text, 'plain'))
  51. if html:
  52. msg.attach(MIMEText(html, 'html'))
  53. # Send the message via local SMTP server.
  54. ret = smtpserver.sendmail(from_addr=conf['gmail_user'], to_addrs=to, msg=msg.as_string())
  55. if ret:
  56. logger.warning(ret)
  57. smtpserver.quit()
  58.  
  59.  
  60. def send_simple_mail(to: str, subject: str = '', text: str = ''):
  61. send_multiple_mail(to=[to], subject=subject, text=text)
  62.  
  63.  
  64. def send_html_mail(to: str, subject: str = '', text: str = '', html: str = ''):
  65. send_multiple_mail(to=[to], subject=subject, text=text, html=html)
  66.  
  67.  
  68. send_simple_mail('test@gmail.com', 'subject test', text='blablabla ...')
  69. send_html_mail('test@gmail.com', 'subject test', text='blablabla ...',
  70. html='<html><body><h1>blablabla ...</h1></body><html>')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement