Created
January 21, 2016 20:56
-
-
Save kpykc/cdd2bba48af3edf8bec9 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 keyring | |
from cStringIO import StringIO | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from email.header import Header | |
from email import Charset | |
from email.generator import Generator | |
import smtplib | |
import nbformat | |
from traitlets.config import Config | |
from nbconvert import HTMLExporter | |
def send(nb_filename, from_address, recipient, subject, credentials): | |
#data = open((this_uri.split('?')[0]).split('/')[-1]).read() | |
data = open(nb_filename).read() | |
this_notebook = nbformat.reads(data, as_version=4) | |
html_exporter = HTMLExporter() | |
html_exporter.template_file = 'full' | |
(body, resources) = html_exporter.from_notebook_node(this_notebook) | |
#open('test.html', 'w').write(body.encode("UTF-8")) | |
# Default encoding mode set to Quoted Printable. Acts globally! | |
Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8') | |
# 'alternative’ MIME type – HTML and plain text bundled in one e-mail message | |
msg = MIMEMultipart('alternative') | |
msg['Subject'] = "%s" % Header(subject, 'utf-8') | |
# Only descriptive part of recipient and sender shall be encoded, not the email address | |
msg['From'] = "\"%s\" <%s>" % (Header(from_address[0], 'utf-8'), from_address[1]) | |
msg['To'] = "\"%s\" <%s>" % (Header(recipient[0], 'utf-8'), recipient[1]) | |
# Attach both parts | |
htmlpart = MIMEText(body, 'html', 'UTF-8') | |
msg.attach(htmlpart) | |
# Create a generator and flatten message object to 'file’ | |
str_io = StringIO() | |
g = Generator(str_io, False) | |
g.flatten(msg) | |
# str_io.getvalue() contains ready to sent message | |
s = smtplib.SMTP('smtp.gmail.com', 587) | |
s.ehlo() | |
s.starttls() | |
s.ehlo() | |
s.login(credentials[1], keyring.get_password(credentials[0], credentials[1])) | |
s.sendmail(msg['From'], [msg['To']], msg.as_string()) | |
from_address = [u'User Name', 'user@gmail.com'] | |
recipient = [u'User Name', 'user@gmail.com'] | |
subject = u'HELLO' | |
nb_filename = 'test_email_report.ipynb' | |
credentials = ("Jupyter Mail Script", "user") | |
#from jupyter_email import send as jm_send | |
#jm_send(nb_filename, from_address, recipient, subject, credentials) | |
send(nb_filename, from_address, recipient, subject, credentials) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment