Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Last active November 19, 2019 18:44
Show Gist options
  • Save drmalex07/9841626 to your computer and use it in GitHub Desktop.
Save drmalex07/9841626 to your computer and use it in GitHub Desktop.
A simple SMTP mailer using Python's smtplib. #python #smtp #mail
import smtplib
import logging
from email.mime.text import MIMEText
class Mailer(object):
def __init__(self, host, port, username, password='', verbose=0):
self.smtp = None
self.host = host
self.port = int(port)
self.username = username
self.password = password
self.verbose = verbose
def connect(self):
if self.smtp:
logging.warn("Allready connected to SMTP endpoint (%s,%d)" %(self.host, self.port))
return
self.smtp = smtplib.SMTP_SSL() # or smtplib.SMTP()
self.smtp.set_debuglevel(self.verbose)
self.smtp.connect(self.host, self.port)
#self.smtp.starttls() # if self.smtp is a plain smtplib.SMTP object
self.smtp.login(self.username, self.password)
return
def send(self, to_addr, headers, body):
msg = MIMEText(body.encode('utf-8'), 'html', 'utf-8')
for h,v in headers.items():
msg[h] = v
if self.smtp is None:
# Try to connect first
self.connect()
from_addr = self.username
self.smtp.sendmail(from_addr, to_addr, msg.as_string())
return
def __del__(self):
if self.smtp:
self.smtp.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment