Created
June 1, 2017 10:15
-
-
Save toast254/dc285e85f60de6a3ee6844af489b0cdb to your computer and use it in GitHub Desktop.
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
# -*- coding: utf-8 -*- | |
import os | |
import json | |
import logging | |
import smtplib | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
logger = logging.getLogger(__name__) | |
config_file = './smtp.gmail.conf' | |
conf = {} | |
""" Configuration file example : | |
{ | |
"gmail_host": "smtp.gmail.com", | |
"gmail_port": 587, | |
"gmail_user": "[email protected]", | |
"gmail_pwd": "password" | |
} | |
""" | |
def load_conf(): | |
global conf | |
if os.path.exists(config_file) and os.path.isfile(config_file): | |
with open(config_file, mode='r', encoding='UTF-8') as file: | |
conf = json.load(file) | |
else: | |
logger.error('Can not found GMAIL SMTP configuration file : ' + config_file) | |
raise FileNotFoundError | |
if not {'gmail_host', 'gmail_port', 'gmail_user', 'gmail_pwd'} <= conf.keys(): | |
logger.error('Invalid GMAIL SMTP configuration in : ' + config_file) | |
raise ValueError | |
load_conf() | |
def send_multiple_mail(to: list, subject: str = '', text: str = '', html: str = ''): | |
smtpserver = smtplib.SMTP(conf['gmail_host'], conf['gmail_port']) | |
smtpserver.ehlo() | |
smtpserver.starttls() | |
smtpserver.login(conf['gmail_user'], conf['gmail_pwd']) | |
# construct mail | |
msg = MIMEMultipart('alternative') | |
msg['Subject'] = subject | |
msg['From'] = conf['gmail_user'] | |
msg['To'] = ", ".join(to) | |
if text or not html: | |
msg.attach(MIMEText(text, 'plain')) | |
if html: | |
msg.attach(MIMEText(html, 'html')) | |
# Send the message via local SMTP server. | |
ret = smtpserver.sendmail(from_addr=conf['gmail_user'], to_addrs=to, msg=msg.as_string()) | |
if ret: | |
logger.warning(ret) | |
smtpserver.quit() | |
def send_simple_mail(to: str, subject: str = '', text: str = ''): | |
send_multiple_mail(to=[to], subject=subject, text=text) | |
def send_html_mail(to: str, subject: str = '', text: str = '', html: str = ''): | |
send_multiple_mail(to=[to], subject=subject, text=text, html=html) | |
send_simple_mail('[email protected]', 'subject test', text='blablabla ...') | |
send_html_mail('[email protected]', 'subject test', text='blablabla ...', | |
html='<html><body><h1>blablabla ...</h1></body><html>') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment