Mailer

  1. import smtplib
  2. import ssl
  3. import threading
  4.  
  5. from email.mime.text import MIMEText
  6.  
  7.  
  8. class Mailer(object):
  9.     def __init__(self, host, port, from_addr=None, usr=None, pwd=None, use_tls=True, use_ssl=True, debug=False):
  10.         self.host = host
  11.         self.port = port
  12.         self.from_addr = from_addr
  13.         self.usr = usr
  14.         self.pwd = pwd
  15.         self.use_tls = use_tls
  16.         self.use_ssl = use_ssl
  17.         if use_ssl:
  18.             self.context = ssl.SSLContext(ssl.PROTOCOL_SSLv3)
  19.         else:
  20.             self.context = None
  21.         self.debug = debug
  22.  
  23.     def send(self, subject, message, recipient, from_addr=None):
  24.         def send():
  25.             msg = MIMEText(message)
  26.             msg['Subject'] = subject
  27.             msg['From'] = from_addr if from_addr else self.from_addr
  28.             if not msg['From']:
  29.                 raise RuntimeError('Unable to define from_addr')
  30.             msg['To'] = recipient
  31.             connection = smtplib.SMTP(self.host, port=self.port)
  32.             connection.set_debuglevel(self.debug)
  33.             if self.use_tls or self.use_ssl:
  34.                 connection.ehlo()
  35.                 connection.starttls(context=self.context)
  36.                 connection.ehlo()
  37.             if self.usr and self.pwd:
  38.                 connection.login(self.usr, self.pwd)
  39.             connection.send_message(msg)
  40.             connection.quit()
  41.         thread = threading.Thread(target=send)
  42.         thread.start()
  43.  
  44.  
  45. def mailer_from_config(config, prefix='mailer.'):
  46.     return Mailer(**{
  47.         key.replace(prefix, ''): value
  48.         for key, value in config.items()
  49.         if key.startswith(prefix)
  50.     })
  51.  
  52. config = {
  53.     'mailer.host': 'smtp.yandex.ru',
  54.     'mailer.port': 25,
  55.     'mailer.debug': True,
  56.     'mailer.usr': 'user',
  57.     'mailer.pwd': 'password',
  58.     'mailer.from_addr': 'user@yandex.ru'
  59. }
  60. mailer = mailer_from_config(config)
  61. mailer.send('Test Mailer', 'Hello!', 'user@gmail.com')
Понадобилось реализовать отправку E-Mail сообщений.
Конечно можно быстро нагуглить кучу примеров, но думаю, что здесь это не помешает.

Реклама

Мы в соцсетях

tw tg yt gt