15.6. 使用Python实现一个geek邮件客户端¶
15.6.1. 开源yagmail发送邮件¶
安装
pip install -U yagmail -i "https://pypi.doubanio.com/simple/" #使用国内的pip源安装yagmail
使用示例:¶
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2020/3/21 9:36
# filename: yagmail01.py
import yagmail
yag = yagmail.SMTP(user='1879324764@qq.com', password="xxxxxxxxx", host='smtp.qq.com', port=25)
content = ['This is the body , and here is just text',
'You can find an image file adn a pdf file attached.',
'iphone6_pic.jpg', 'redbooks.pdf']
yag.send("962057147@qq.com", 'This mail come from yagmail', content)
yag.close()
使用上下文管理器优化关闭连接的逻辑,使代码更加清晰易懂。
#!/usr/bin/env python
# -*- coding:utf8 -*-
# auther; 18793
# Date:2020/3/21 9:36
# filename: yagmail02.py
import yagmail
content = ['This is the body , and here is just text',
'You can find an image file adn a pdf file attached.',
'iphone6_pic.jpg', 'redbooks.pdf']
with yagmail.SMTP(user='1879324764@qq.com', password="tpuvxqftwjujeaja", host='smtp.qq.com', port=25) as yag:
yag.send("962057147@qq.com", 'This mail come from yagmail', content)
配置文件信息
[root@k8s-master ~]# cat ~/.emcli.cnf
[DEFAULT]
smtp_server = smtp.qq.com
smtp_port = 25
username = 1879324764@qq.com
password = tpuvxqftwjujeaja
emcli的功能实现¶
解析命令行参数¶
def get_argparse():
parser = argparse.ArgumentParser(description='A email client in terminal')
parser.add_argument('-s', action='store', dest='subject', required=True, help='specify a subject (must be in quotes if it has spaces)')
parser.add_argument('-a', action='store', nargs='*', dest='attaches', required=False, help='attach file(s) to the message')
parser.add_argument('-f', action='store', dest='conf', required=False, help='specify an alternate .emcli.cnf file')
parser.add_argument('-r', action='store', nargs='*', dest='recipients', required=True, help='recipient who you are sending the email to')
parser.add_argument('-v', action='version', version='%(prog)s 0.2')
return parser.parse_args()
解析配置文件内容¶
def get_config_file(config_file):
if config_file is None:
config_file = os.path.expanduser('~/.emcli.cnf')
return config_file
def get_meta_from_config(config_file):
config = ConfigParser.SafeConfigParser()
with open(config_file) as fp:
config.readfp(fp)
meta = Storage()
for key in ['smtp_server', 'smtp_port', 'username', 'password']:
try:
val = config.get('DEFAULT', key)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as err:
logger.error(err)
raise SystemExit(err)
else:
meta[key] = val
return meta
使用yagmail发送电子邮件¶
def send_email(meta):
content = get_email_content()
body = [content]
if meta.attaches:
body.extend(meta.attaches)
with yagmail.SMTP(user=meta.username, password=meta.password,
host=meta.smtp_server, port=int(meta.smtp_port)) as yag:
logger.info('ready to send email "{0}" to {1}'.format(meta.subject, meta.recipients))
ret = yag.send(meta.recipients, meta.subject, body)
log日志打印的辅助函数¶
import logging
def get_logger(log_level=logging.INFO):
logger = logging.getLogger(__name__)
logger.setLevel(log_level)
formatter = logging.Formatter("%(asctime)s [emcli] [%(levelname)s] : %(message)s", "%Y-%m-%d %H:%M:%S")
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.handlers = [handler]
return logger
使用setuptools打包源码¶
setup.py
#!/usr/bin/env python
# coding: utf-8
from setuptools import setup
setup(
name='emcli',
version='0.2',
author='Mingxing LAI',
author_email='me@mingxinglai.com',
url='https://github.com/lalor/emcli',
description='A email client in terminal',
packages=['emcli'],
install_requires=['yagmail'],
tests_require=['nose', 'tox'],
entry_points={
'console_scripts': [
'emcli=emcli:main',
]
}
)
本机安装和运行
python setup.py install
如果要安装到其他机器上
python setup.py sdist
会在emcli\dist 的目录下生成一个emcli-0.2.tar.gz的文件
使用twine上传到PyPi¶
在Python生态中,工程师已经习惯了使用pip 命令安装软件包。
为了让最终用户可以使用pip 命令安装emcli 项目,
我们需要将emcli发布到PyPI(http://pypi.python.org)上。
因此, 我们需要在PyPI上注册一个账号。账号注册完成以后,在HOME
目录下创建一个.pypirc文件, 并在文件中填人PyPi的 用户名和密码:
[pypi]
username:<your username>
password:<your password>
配置好用户名和密码以后, 还需要安装一个名为twine的小工具。
是一个将软件包上传到PyPI 上的工具。如下所示:
pip install twine
使用twine将emcli上传到PyPI :
twine dist/*
上传完成以后,任何人都可以在自己的电脑上使用pip命令安装我们的命令行邮件客户端。
参考如下:
https://github.com/lalor/emcli