Конечно можно быстро нагуглить кучу примеров, но думаю, что здесь это не помешает.
import smtplib
import ssl
import threading
from email.mime.text import MIMEText
class Mailer(object):
def __init__(self, host, port, from_addr=None, usr=None, pwd=None, use_tls=True, use_ssl=True, debug=False):
self.host = host
self.port = port
self.from_addr = from_addr
self.usr = usr
self.pwd = pwd
self.use_tls = use_tls
self.use_ssl = use_ssl
if use_ssl:
self.context = ssl.SSLContext(ssl.PROTOCOL_SSLv3)
else:
self.context = None
self.debug = debug
def send(self, subject, message, recipient, from_addr=None):
def send():
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = from_addr if from_addr else self.from_addr
if not msg['From']:
raise RuntimeError('Unable to define from_addr')
msg['To'] = recipient
connection = smtplib.SMTP(self.host, port=self.port)
connection.set_debuglevel(self.debug)
if self.use_tls or self.use_ssl:
connection.ehlo()
connection.starttls(context=self.context)
connection.ehlo()
if self.usr and self.pwd:
connection.login(self.usr, self.pwd)
connection.send_message(msg)
connection.quit()
thread = threading.Thread(target=send)
thread.start()
def mailer_from_config(config, prefix='mailer.'):
return Mailer(**{
key.replace(prefix, ''): value
for key, value in config.items()
if key.startswith(prefix)
})
config = {
'mailer.host': 'smtp.yandex.ru',
'mailer.port': 25,
'mailer.debug': True,
'mailer.usr': 'user',
'mailer.pwd': 'password',
'mailer.from_addr': '[email protected]'
}
mailer = mailer_from_config(config)
mailer.send('Test Mailer', 'Hello!', '[email protected]')