<s> import smtplib <EOL> import getpass <EOL> import subprocess <EOL> try : <EOL> import keyring <EOL> except ImportError : <EOL> keyring = None <EOL> import email . mime . multipart <EOL> import email . mime . text <EOL> import email . utils <EOL> class Mailer ( object ) : <EOL> def send ( self , msg ) : <EOL> raise NotImplementedError <EOL> def msg_plain ( self , from_email , to_email , subject , body ) : <EOL> msg = email . mime . text . MIMEText ( body , '<STR_LIT>' , '<STR_LIT>' ) <EOL> msg [ '<STR_LIT>' ] = subject <EOL> msg [ '<STR_LIT>' ] = from_email <EOL> msg [ '<STR_LIT>' ] = to_email <EOL> msg [ '<STR_LIT>' ] = email . utils . formatdate ( ) <EOL> return msg <EOL> def msg_html ( self , from_email , to_email , subject , body_text , body_html ) : <EOL> msg = email . mime . multipart . MIMEMultipart ( '<STR_LIT>' ) <EOL> msg [ '<STR_LIT>' ] = subject <EOL> msg [ '<STR_LIT>' ] = from_email <EOL> msg [ '<STR_LIT>' ] = to_email <EOL> msg [ '<STR_LIT>' ] = email . utils . formatdate ( ) <EOL> msg . attach ( email . mime . text . MIMEText ( body_text , '<STR_LIT>' , '<STR_LIT>' ) ) <EOL> msg . attach ( email . mime . text . MIMEText ( body_html , '<STR_LIT:html>' , '<STR_LIT>' ) ) <EOL> return msg <EOL> class SMTPMailer ( Mailer ) : <EOL> def __init__ ( self , smtp_server , smtp_port , tls , auth ) : <EOL> self . smtp_server = smtp_server <EOL> self . smtp_port = smtp_port <EOL> self . tls = tls <EOL> self . auth = auth <EOL> def send ( self , msg ) : <EOL> s = smtplib . SMTP ( self . smtp_server , self . smtp_port ) <EOL> s . ehlo ( ) <EOL> if self . tls : <EOL> s . starttls ( ) <EOL> if self . auth and keyring is not None : <EOL> passwd = keyring . get_password ( self . smtp_server , msg [ '<STR_LIT>' ] ) <EOL> if passwd is None : <EOL> raise ValueError ( '<STR_LIT>' . format ( self . smtp_server , msg [ '<STR_LIT>' ] ) ) <EOL> s . login ( msg [ '<STR_LIT>' ] , passwd ) <EOL> s . sendmail ( msg [ '<STR_LIT>' ] , [ msg [ '<STR_LIT>' ] ] , msg . as_string ( ) ) <EOL> s . quit ( ) <EOL> class SendmailMailer ( Mailer ) : <EOL> def __init__ ( self , sendmail_path ) : <EOL> self . sendmail_path = sendmail_path <EOL> def send ( self , msg ) : <EOL> p = subprocess . Popen ( [ self . sendmail_path , '<STR_LIT>' , '<STR_LIT>' ] , <EOL> stdin = subprocess . PIPE , <EOL> stderr = subprocess . PIPE , <EOL> universal_newlines = True ) <EOL> result = p . communicate ( msg . as_string ( ) ) <EOL> if p . returncode : <EOL> logger . error ( '<STR_LIT>' . format ( result = result ) ) <EOL> def set_password ( smtp_server , from_email ) : <EOL> '''<STR_LIT>''' <EOL> if keyring is None : <EOL> raise ImportError ( '<STR_LIT>' ) <EOL> password = getpass . getpass ( prompt = '<STR_LIT>' . format ( from_email , smtp_server ) ) <EOL> keyring . set_password ( smtp_server , from_email , password ) </s>
