Python - eMail

From Torben's Wiki

Simple Text Mails

A simple class that can be used to send text messages via eMail.

import smtplib
class Mailer1():
  def __init__(self, parent = None):
    self.SENDER = 'Sender <sender@host.com>'
    self.RECIPIENTS = ['Receiver <receiver@host.com>']
    self.smtpserver = 'host.com'
    self.AUTHREQUIRED = 0 # if you need to use SMTP AUTH set to 1
    self.smtpuser =   # for SMTP AUTH, set SMTP username here
    self.smtppass =   # for SMTP AUTH, set SMTP password here

  def send(self, text):
    session = smtplib.SMTP(self.smtpserver)
    if self.AUTHREQUIRED:
        session.login(smtpuser, smtppass)
    smtpresult = session.sendmail(self.SENDER, self.RECIPIENTS, text)
    session.quit()

Attach Files

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os

class Mailer2():
  def __init__(self, parent = None):
    self.SENDER = 'Sender <sender@host.com>'
    self.RECIPIENTS = ['Receiver <receiver@host.com>,']
    self.smtpserver = 'host.com'
    self.AUTHREQUIRED = 0 # if you need to use SMTP AUTH set to 1
    self.smtpuser =   # for SMTP AUTH, set SMTP username here
    self.smtppass =   # for SMTP AUTH, set SMTP password here

  def send(self, subject, text, files=[]): # files=[]
    to = self.RECIPIENTS
    assert type(to)==list
    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = self.SENDER
    msg['To'] = COMMASPACE.join(to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject
    msg.attach( MIMEText(text) )

    for file in files:
      part = MIMEBase('application', "octet-stream")
      part.set_payload( open(file,"rb").read() )
      Encoders.encode_base64(part)
      part.add_header('Content-Disposition', 'attachment; filename="%s"'
                     % os.path.basename(file))
      msg.attach(part)

    smtp = smtplib.SMTP(self.smtpserver)
    if self.AUTHREQUIRED:
      smtp.login(self.smtpuser, self.smtppass)
    smtp.sendmail(self.SENDER, to, msg.as_string() )
    smtp.close()