使用docopt/schema:markdown文件直接发送支持python语法的邮件

前言

  1. 工作经常写一些东西发邮件,但是渐渐的已经用markdown写东西,每次很纠结,
  2. 而且还需要我打开邮箱,然后balabala,比如我还要在后面加入公司和自己的一些信息
  3. 经常邮件或者html都带有python的源码段,想要一个支持python语法的css显示效果

    使用的模块

  • docopt Pythonic的命令行函数解析,只需要把显示的参数列表放在 doc
  • schema Pythonic的数据结构验证,不需要那么多的异常处理
  • markdown
  • PyYAML 解析yaml文件
  • pygments 借用它对python语法的一些正则匹配
  • requests 我没有自己实现css,css可以本地自己自定义,也可以从网站下载,这里去爬网站的css文件
    PS:安装这些可以
1
2

sudo easy_install schema docopt markdown pygments pyyaml

功能

  • 支持python语法
  • 支持本地有配置文件,不需要命令行balabala那么多(使用yaml)
  • 支持多种颜色方案,方案可选项: pygments-css
  • 支持本地自定义css(默认去这个网站爬回来)
  • 支持中文
  • 支持自定义html模板文件,比如我们公司邮件下部的联系方式等说明,可以放在模板邮件里面
  • 可以不发送邮件,只保留和加了css后的html到本地文件

    使用举例

  1. 默认模式
1
2
3

python MarkPygments.py --mailto mailto@qq.com,mailto2@qq.com -s 标题 --mailserver smtp.exmail.qq.com -u youremailname
-p yourpassword --cc cc@qq.com whatever.md --template template.html
  1. 使用本地yaml配置,配置如下, 配置中没有能命令行选项找,配置和终端都有会使用中有文件配置
    这是yaml文件的内容:
1
2
3
4
5
6
7
8

markemail:
--theme: autumn
--username: XX
--password: YY
--mailserver: smtp.exmail.qq.com
--mailto: to1@qq.com,to2@qq.com
--subject: '周报'

然后这样使用:

1
2

python MarkPygments.py --config ~/.config.yaml whatever.md --template template.html
  1. 使用本地css目录下的css, 不发送邮件只保存html到本地文件
1
2
3

python MarkPygments.py --config ~/.config.yaml whatever.md --template template.html
-o out.html --local pygments-css

这里是代码,或者你可以去看MarkPygments.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306

# coding=utf-8
'''
Usage:
MarkPygments.py [options] MDFILE
MarkPygments.py [options] --local <cssdir> MDFILE
MarkPygments.py [options] --config <yamlfile> MDFILE

Arguments:
MDFILE the markdown file
-u --username user your email name
-p --password pass your email login password
-mt --mailto tolist mailto list
--theme theme css style for python syntax [default: monokai]
-s --subject subject email's subject
--mailserver server mail server [default: smtp.exmail.qq.com]

Options:
-h --help show this help message and exit
--version show version and exit
--config yamlfile config yaml file path (e.g. .config.yaml)
--local cssdir use local custom css dir
-o --output [outhtml] make output to html file
-c --cc list cc list
--template html template html

'''


import os
import re
import codecs
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import markdown
from docopt import docopt
from schema import Schema, And, Or, Use, SchemaError


def log(message, error=False):
'''终端输出log'''
color = 31 if error else 32
print '\x1B[1;{0}m * {1}\x1B[0m'.format(color, message)


def regex():
'''借用pygments对python语法的实现以及自己实现的正则'''
from pygments.lexers import PythonLexer
dict = {}
lex = PythonLexer()
token = lex.tokens
l = ['keywords', 'builtins']
for i in l:
dict[i[:2]] = token[i][0][0]
dict['fu'] = '.*(def)\W+(.*)\((.*)\)'
dict['cl'] = '.*(?!<span)(class)(?!=)\W+(?!=)(.*)\((.*)\)'
dict['fm'] = '.*(from)\W+(.*)\W+(import)\W+(.*)'
dict['im'] = '.*(import)\W\{,\4}(.*)'
return dict


def sendMail(mailserver, username, password, tolist, subject, msg, cc=[]):
'''发送邮件'''
def makeEmail(content):

msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = username
msg['To'] = ','.join(tolist)
if cc:
msg['Cc'] = ','.join(cc)
html_part = MIMEText(content, 'html', 'utf-8')
msg.attach(html_part)
return msg
try:

smtp = smtplib.SMTP()
log('Connect to {0}'.format(mailserver))
smtp.connect(mailserver, 25)
smtp.login(username, password)
log('Login Success with {0}'.format(username))
log('To send this Email...')
if cc:
smtp.sendmail(username, tolist + cc, makeEmail(msg).as_string())
else:
smtp.sendmail(username, tolist, makeEmail(msg).as_string())
log('Send Success')
except Exception, e:
log(e, error=True)


def paserYaml(yamlfile):
'''解析yaml文件配置'''
import yaml
return yaml.load(open(yamlfile)).get('markemail', {})


def check_email(emails):
'''检查选项是否是邮件格式'''
print emails
regex = r'''^[_a-z0-9-]+(\.[a-z0-9-]+)*@[a-z0-9-]+
(\.[a-z0-9-]+)*(\.[a-z]{2,3})$'''
rst = map(lambda n: True if re.compile(
regex).match(n) else False, emails.split(','))
return True if False not in rst else False


def colorClass():
'''pygments-css对语法的class对应字典'''
return dict(
cl=['k', 'nc', 'nb'],
fu=['k', 'nf', 'bp'],
fm=['nd', 'vi', 'nd', 'vi'],
im=['nd', 'mi'],
ke=['kd'],
bu=['vc']
)


class cssStyle(object):

'''获取css设置'''
def __init__(self, style, *args):

self.style = style
self.args = args

def fusionCss(self, csshtml):

css = '<style type="text/css">'
css += '.codehilite {border: 2px solid rgb(225, 225, 225)}'
css += csshtml
css += '</style>'
return css

def local(self, cssdir, theme):
'''从本地css文件'''
log('Fetch css from local dir:{0}'.format(cssdir))
with open('{0}/{1}.css'.format(cssdir, theme)) as f:
css = f.read().strip()
return self.fusionCss(css)

def crawler(self, theme):
'''去这个网站爬回来'''
import requests
log('Fetch css from site:igniteflow.com')
r = requests.get(
'http://igniteflow.com/static/css/pygments/{0}.css'.format(theme))
return self.fusionCss(r.text.strip())

def main(self):

return getattr(self, self.style)(*self.args)


class FabricHtml(object):

def __init__(self, md, css):

self.css = css
self.md_html = self.makeToHtml(md)

def makeToHtml(self, md):

log('Markdown converted into html')
input_file = codecs.open(md, mode="r", encoding="utf-8")
text = input_file.read()
return markdown.markdown(text)

def AddCssToHtml(self, html, css_html):
'''增加css的style'''
ohtml = css_html
c = html.split('```')
inc = 0
ohtml += c[0]
for inc in range(1, len(c[1:]) + 1):
if inc % 2:
ohtml += '<div class="codehilite">'
else:
ohtml += '</div>'
ohtml += c[inc]
inc += 1
return ohtml

def makeSpan(self, html, c):
'''构造span包含符合的语法块'''
if not html:
return ''

return '<span class="{0}">{1}</span>'.format(c, html)

def markHtml(self, h):
'''给html加python语法的颜色css'''
for k, v in regex().items():
args = colorClass()[k]
m = re.compile(r'%s' % v).match(h)
if m:
match = m.groups()
for i in range(len(args)):
h = re.sub(match[i], self.makeSpan(
match[i], args[i]), h, 1)
return h

def main(self, template=''):

has_css_html = self.AddCssToHtml(self.md_html, self.css)
return self.pygments(has_css_html) + template

def pygments(self, html):

log('Mark span label with python syntax')
ohtml = ''
for h in html.split('\n'):
ohtml += self.markHtml(h)
ohtml += '\n'
return ohtml


def checkSchema(schemadict, args):
'''Pythonic的检查schema'''
schema = Schema(schemadict)
try:
args = schema.validate(args)
except SchemaError as e:
raise
exit(log(e, error=True))
return args


def main():

args = docopt(__doc__, version='1.0r1')

isLocal = args.get('--local')
hasConfig = args.get('--config')
theme = args.get('--theme')
if hasConfig:
checkSchema({
'--config': And(Use(str),
os.path.exists,
error='Invalid config format or not exists')
}, {'--config': hasConfig}
)
yamlConfig = paserYaml(hasConfig)
args.update(yamlConfig)
args.pop('--config')

if isLocal:
checkSchema({
'--local': And(Use(str), os.path.isdir,
lambda n: os.path.exists('{0}/{1}.css'.format(
n, theme)), error=
'Invalid custom css dir or hasnot this theme'),
}, {'--local': isLocal}
)
css_dict = cssStyle('local', isLocal, theme).main()
else:
css_dict = cssStyle('crawler', theme).main()
args.pop('--local')
args.pop('--theme')
args = checkSchema({
'MDFILE': os.path.exists,
'--mailserver': Use(str, error='Invalid server format'),
'--mailto': And(Use(str), lambda n: check_email(n),
error='Invalid email format'),
'--subject': Or(Use(str), Use(unicode),
error='Invalid suject format'),
'--password': Use(str, error='Invalid suject format'),
'--cc': Or(None, And(Use(str), lambda n: check_email(n)),
error='Invalid email format'),
'--output': Or(False, lambda n: os.path.exists(
os.path.dirname('{0}/{1}'.format(
os.path.abspath('.'), n))),
error='Dir must exists'),
'--template': Or(None, os.path.exists, error='template must exists'),
'--username': Use(check_email, error='Invalid username format'),
'--help': Or(False, True),
'--version': Or(False, True)
}, args)
do = FabricHtml(args['MDFILE'], css_dict)
cc = args['--cc'].split(',') if args['--cc'] else []

if args['--template']:
with codecs.open(args['--template'], mode="r", encoding="utf-8") as f:
html_content = do.main(f.read())
else:
html_content = do.main()
if args['--output']:
with codecs.open(args['--output'], mode="w", encoding="utf-8") as f:
f.write(html_content)
exit()

sendMail(
args['--mailserver'],
args['--username'],
args['--password'],
args['--mailto'].split(','),
args['--subject'],
html_content,
cc
)

if __name__ == '__main__':

main()

版权声明:本文由 董伟明 原创,未经作者授权禁止任何微信公众号和向掘金(juejin.im)转载,技术博客转载采用 保留署名-非商业性使用-禁止演绎 4.0-国际许可协议
python