Python - eMail
SMTP eMail Sending
#!/usr/bin/env python3 # from https://stackoverflow.com/a/64890 from email.mime.text import MIMEText from email.utils import formatdate, make_msgid # this invokes the secure SMTP protocol (port 465, uses SSL) from smtplib import SMTP_SSL as SMTP def smtp_connect(smtp_server, smtp_username, smtp_password): conn = SMTP(smtp_server) conn.set_debuglevel(False) conn.login(smtp_username, smtp_password) if VERBOSE: print("SMTP connected") return conn def smtp_send(smtp_conn, mail_to, mail_subject, mail_body): # typical values for text_subtype are plain, html, xml mail_text_subtype = "plain" msg = MIMEText(mail_body, mail_text_subtype) msg["Date"] = formatdate() # important to add, since not all smtp servers add missing fields msg['Message-ID'] = make_msgid(domain="entorb.net") # same msg["From"] = mail_from msg["To"] = mail_to msg["Subject"] = mail_subject print(msg.as_string()) smtp_conn.sendmail(mail_from, mail_to, msg.as_string()) smtp_conn.quit()
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()