用Markdown写邮件,用Python发邮件

平时工作过程中不免要应用邮件,现有的邮件客户端在编辑体验上都不怎么敌对,在调整格局时尤其苦楚。以我的无限的人生教训来看,所见即所得的编辑软件往往不如纯文本编辑体验晦涩。近些年来,Markdown逐步成为写作的利器,甚至当初有些出版社也曾经接管Markdown手稿。
那么,咱们是否应用Markdown来写邮件呢,而后写个Python小脚本去发送邮件呢?

邮件通信的内容应用MIME(Multipurpose Internet Mail Extension)编码,MIME之于邮件客户端相似于html之于浏览器的关系。MIME反对邮件承载多媒体内容,能够把MIME了解为受限的html/css,然而MIME不反对js脚本(平安起因)。

整个程序的工作原理如下图:

在本人喜爱的Markdown编辑器下编辑markdown文档/邮件

记得在markdown文档头部增加formatter

From: 吴志国 <wuzhiguo_carter@qq.com>To: 吴志国 <wuzhiguo_carter@qq.com>Subject: 测试Markdown邮件---

配置集体邮箱账号、明码(切记不要在公共电脑寄存集体明码,也不要上传到公网)

能够寄存到~/.markdown-to-email.json

{    "username": "your_account",     "smtp": "smtp.qq.com:587",     "password": "your password/authorization code" }
QQ邮箱服务在应用第三方客户端登录时,须要申请受权码。详见:什么是受权码,它又是如何设置?

执行如下的Python代码

残缺示例,参考git仓库: https://gitee.com/dearyiming/...

本地预览

python markdown_email.py -p --md <your markdown file>

发送邮件

python markdown_email.py -s --md <your markdown file>
#!/usr/bin/env python'''Send an multipart email with HTML and plain text alternatives. The messageshould be constructed as a plain-text file of the following format:        From: Your Name <your@email.com>    To: Recipient One <recipient@to.com>    Subject: Your subject line    ---    Markdown content hereThe script accepts content from stdin and, by default, prints the rawgenerated email content to stdout.Preview your message on OS X by invoking the script with `-p` or `--preview`, and it will open in your default mail client.To send the message, invoke with `-s` or `--send`. You must have aJSON file in your home directory named `.markdown-to-email.json`with the following keys:    {        "username": "smtp-username",         "smtp": "smtp.gmail.com:587",         "password": "your-password"     }Enjoy!'''import osimport sysimport jsonimport argparseimport smtplibimport subprocessfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport pygmentsimport markdown2 as markdown# define argumentsparser = argparse.ArgumentParser(description='Format and send markdown-based emails.',                                 formatter_class=argparse.RawDescriptionHelpFormatter,                                 epilog=__doc__)parser.add_argument('-p', '--preview', action='store_true',                     help='Preview the email in Apple Mail.')parser.add_argument('-s', '--send', action='store_true',                     help='Send the email using your configuration.')parser.add_argument('--md', dest='markdown', type=str, nargs=1, required=True)args = parser.parse_args()print(args)# read in raw message contentraw_content = open(args.markdown[0], 'r').read()# split out the headers from the markdown message bodyheader_content, markdown_content = raw_content.split('---', 1)# render the markdown into HTML css = subprocess.check_output(['pygmentize', '-S', 'default', '-f', 'html'])markdown_content = markdown_content.strip()html_content = markdown.markdown(markdown_content)html_content = ''.join([    '<style type="text/css">',    str(css),    '</style>',    html_content])# create a multipart email messagemessage = MIMEMultipart('alternative')# parse the headersheaders = {}for line in header_content.strip().split('\n'):    if not line.strip(): continue    key, value = line.split(':', 1)    headers[key.strip()] = value.strip()# set the headersmessage['To'] = headers.get('To', '')message['From'] = headers.get('From', '')message['Subject'] = headers.get('Subject', 'No subject')# attach the message partsmessage.attach(MIMEText(markdown_content, 'plain')) # 如果邮件客户端不反对html,显示Markdown源码message.attach(MIMEText(html_content, 'html')) # 如果邮件客户端反对html,显示Markdown渲染后的htmlif args.send:    to = message['To'].split(', ')        with open(os.path.expanduser('~/.markdown-to-email.json'), 'rb') as f:        config = json.loads(f.read())        server = smtplib.SMTP(config['smtp'])        server.starttls()        server.login(config['username'], config['password'])        server.sendmail(message['From'], to, message.as_string())        server.quit()elif args.preview:    email_dump = '/tmp/preview-with-css.eml'    open(email_dump, 'w').write(message.as_string())    os.system('open -a Mail {}'.format(email_dump))else:    print(message.as_string())

邮件成果

参考信息

  1. 了解邮件传输协定(SMTP、POP3、IMAP、MIME)
  2. cleverdevil/markdown-to-email

    本文由博客一文多发平台 OpenWrite 公布!