Skip to content

Instantly share code, notes, and snippets.

@adoc
Created February 14, 2015 09:52
Show Gist options
  • Save adoc/7e1ae374b50292bcbd2b to your computer and use it in GitHub Desktop.
Save adoc/7e1ae374b50292bcbd2b to your computer and use it in GitHub Desktop.
sendmail.py3 - Small sendmail lib for Python 3
import logging
log = logging.getLogger(__name__)
import codecs
from subprocess import Popen, PIPE
from email.mime.multipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart
from email.mime.text import MIMEText
class Basemail(object):
def encode(self, mailfrom, rcptto, subject, replyto=None, cc=None,
bcc=None, htmlpart='', textpart='', charset='utf-8'):
if htmlpart and textpart:
message = MIMEMultipart('alternative')
elif htmlpart:
message = MIMENonMultipart('text','html')
elif textpart:
message = MIMENonMultipart('text','plain')
else:
return None
message['From'] = str(mailfrom)
message['To'] = ', '.join(rcptto) if isinstance(rcptto,list) else rcptto
message['Subject'] = str(subject)
if replyto:
message['Reply-To'] = str(replyto)
if cc:
message['Cc'] = ', '.join(cc) if isinstance(cc,list) else cc
if bcc:
message['Bcc'] = ', '.join(bcc) if isinstsance(bcc,list) else bcc
htmlpart = codecs.encode(htmlpart, charset)
textpart = codecs.encode(textpart, charset)
if htmlpart and textpart:
plaintext = MIMEText(textpart.decode(), 'plain')
htmltext = MIMEText(htmlpart.decode(), 'html')
message.attach(plaintext)
message.attach(htmltext)
elif htmlpart:
message.set_payload(htmlpart, charset=charset)
elif textpart:
message.set_payload(textpart, charset=charset)
else:
return None
self.message = message # Compatibility with old api.
return message
class SendMail(Basemail):
def __init__(self, sendmail_path='/usr/sbin/sendmail'):
self.sendmail_path = sendmail_path
def send(self, *args):
if args:
message = args[0]
else:
message = self.message # Compatibility with old api.
sendmail = Popen([self.sendmail_path, "-t"], stdin=PIPE)
sendmail.communicate(message.as_string().encode())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment