Skip to content

Instantly share code, notes, and snippets.

@sharpevo
Last active August 29, 2015 14:23
Show Gist options
  • Save sharpevo/ea55ba300d0f1aec1d53 to your computer and use it in GitHub Desktop.
Save sharpevo/ea55ba300d0f1aec1d53 to your computer and use it in GitHub Desktop.
import smtplib
from email.mime.text import MIMEText
import traceback
class MailSender():
"""
Send mails by smtplib with easy interfaces.
"""
def __init__(self, host="smtp.live.com", port="25", auto_cc=False):
self.host = host
self.port = port
self.auto_cc = auto_cc
def authenticated(self, username="", password=""):
self.username = username
self.password = password
self.server = smtplib.SMTP()
self.server.connect(self.host, self.port)
self.server.starttls()
try:
self.server.login(self.username, self.password)
except Exception as e:
return False
return True
def compose(self, to=[], subject="", message=""):
if isinstance(to, str):
self.receiver = [to]
elif isinstance(to, list):
self.receiver = to
if self.auto_cc:
self.receiver.append(self.username)
if isinstance(message, str):
self.message = """From: %s\r\nTO: %s\r\nSubject: %s\r\n
%s
""" % (self.username, ", ".join(self.receiver), subject, message)
elif isinstance(message, MIMEText):
message["Subject"] = subject
message["From"] = self.username
message["To"] = ", ".join(self.receiver)
self.message = message.as_string()
def send(self):
try:
self.server.sendmail(self.username, self.receiver, self.message)
except Exception as e:
print traceback.print_exc()
finally:
self.server.quit()
if __name__ == "__main__":
ms = MailSender()
if ms.authenticated(username="yangwupek@outlook.com", password="----------"):
ms.compose(to=["yangwuist@outlook.com","sharpevo@outlook.com"],
subject="test again",
message="This is a test from MailSender Object\r\n TEST")
ms.send()
ms.compose(to="sharpevo@outlook.com",
subject="test again",
message="Only to sharpevo\r\n TEST")
ms.send()
ms.compose(to=["yangwuist@outlook.com","sharpevo@outlook.com"],
subject="test again",
message=MIMEText("""Send from <b>Python</b><br/>Regards""",
"html",
"utf-8"))
ms.send()
ms.compose(to="sharpevo@outlook.com",
subject="test again",
message=MIMEText("""Send from <b>Python</b><br/>Regards""",
"html",
"utf-8"))
ms.send()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment