Created
August 19, 2014 04:19
-
-
Save adoc/b82587e3efb262bde703 to your computer and use it in GitHub Desktop.
sendmail.py - Simple sendmail hook including email packaging.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import logging | |
log = logging.getLogger(__name__) | |
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 = htmlpart.encode(charset) | |
textpart = textpart.encode(charset) | |
if htmlpart and textpart: | |
plaintext = MIMEText(textpart, 'plain') | |
htmltext = MIMEText(htmlpart, '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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment