关于python:用Markdown写邮件用Python发邮件

39次阅读

共计 3715 个字符,预计需要花费 10 分钟才能阅读完成。

用 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 message
should 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 here
The script accepts content from stdin and, by default, prints the raw
generated 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 a
JSON 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 os
import sys
import json
import argparse
import smtplib
import subprocess

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import pygments
import markdown2 as markdown

# define arguments
parser = 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 content
raw_content = open(args.markdown[0], 'r').read()

# split out the headers from the markdown message body
header_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 message
message = MIMEMultipart('alternative')

# parse the headers
headers = {}
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 headers
message['To'] = headers.get('To', '')
message['From'] = headers.get('From', '')
message['Subject'] = headers.get('Subject', 'No subject')

# attach the message parts
message.attach(MIMEText(markdown_content, 'plain')) # 如果邮件客户端不反对 html,显示 Markdown 源码
message.attach(MIMEText(html_content, 'html')) # 如果邮件客户端反对 html,显示 Markdown 渲染后的 html

if 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 公布!

正文完
 0