文章目录
python学习的第二十四天:对Word、邮件和短信的操作
操作word需要的工具
安装三方库
python-docx —> pip install python-docx pillow
pillow —> PIL —> Python Image Library,图片处理工具
对Word的读写操作
基本操作方法
from docx import Document
from docx.shared import Cm, Pt
from docx.document import Document as Doc
# 在"#"后放入"type:"可以告知python赋值的数据类型,目的为使python不会因为无法确定数据类型而取消函数补充
document = Document() # type: Doc
# 添加大标题
document.add_heading('快快乐乐学Python', 0)
# 添加段落
p = document.add_paragraph('Python是一门非常流行的编程语言,它')
run = p.add_run('简单')
# 加粗
run.bold = True
# 设置字体大小
run.font.size = Pt(18)
# 斜体
p.add_run('而且').italic = True
run = p.add_run('优雅')
run.font.size = Pt(18)
# 下划线
run.underline = True
p.add_run('。')
# 添加一级标题
document.add_heading('Heading, level 1', level=1)
# 添加带样式的段落
document.add_paragraph('Intense quote', style='Intense Quote')
# 添加无序列表
document.add_paragraph(
'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
'second item in ordered list', style='List Bullet'
)
# 添加有序列表
document.add_paragraph(
'first item in ordered list', style='List Number'
)
document.add_paragraph(
'second item in ordered list', style='List Number'
)
# 添加图片
document.add_picture('resources/guido.jpg', width=Cm(5.2))
# 添加分节符
document.add_section()
records = (
('小明', '男', '2012-12-20'),
('小红', '女', '1999-9-9')
)
# 添加表格
table = document.add_table(rows=1, cols=3)
table.style = 'Dark List'
hdr_cells = table.rows[0].cells
hdr_cells[0].text = '姓名'
hdr_cells[1].text = '性别'
hdr_cells[2].text = '出生日期'
for name, sex, birthday in records:
row_cells = table.add_row().cells
row_cells[0].text = name
row_cells[1].text = sex
row_cells[2].text = birthday
# 添加分页符
document.add_page_break()
# 保存文档
document.save('resources/demo.docx')
Python读取Word文档并替换指定内容
from docx import Document
from docx.document import Document as Doc
doc = Document('resources/离职证明.docx') # type: Doc
# 对所有段落进行循环遍历
for p in doc.paragraphs:
if '周杰' in p.text:
# 对段落中的元素进行循环遍历
for run in p.runs:
if '周杰' in run.text:
run.text = run.text.replace('周杰', '周杰伦')
doc.save('resources/离职证明.docx')
基于样板文档批量创建Word文档
from docx import Document
from docx.document import Document as Doc
employees = [
{
'name': '小明',
'id': '100200198011280001',
'sdate': '2008年3月1日',
'edate': '2012年2月29日',
'department': '产品研发',
'position': '架构师'
},
{
'name': '小红',
'id': '510210199012125566',
'sdate': '2019年1月1日',
'edate': '2021年4月30日',
'department': '产品研发',
'position': 'Python开发工程师'
},
{
'name': '小亮',
'id': '2102101995103221599',
'sdate': '2020年5月10日',
'edate': '2021年3月5日',
'department': '产品研发',
'position': 'Java开发工程师'
},
]
for emp_dict in employees:
doc = Document('resources/离职证明模板.docx') # type: Doc
for p in doc.paragraphs:
if '{' not in p.text:
continue
for run in p.runs:
if '{' not in run.text:
continue
# 将占位符换成实际内容
start, end = run.text.find('{'), run.text.find('}')
key, place_holder = run.text[start + 1:end], run.text[start:end + 1]
run.text = run.text.replace(place_holder, emp_dict[key])
doc.save(f'resources/{emp_dict["name"]}离职证明.docx')
操作邮件需要的工具
smtplib
Header
MIMEMultipart
MIMEText
quote
书写和发送邮件
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from urllib.parse import quote
def create_attachment(path, filename):
with open(f'{path}/{filename}', 'rb') as file:
attachment = MIMEText(file.read(), 'base64', 'utf-8')
# 指定内容类型
attachment['content-type'] = 'application/octet-stream'
# 将文件名处理成百分号编码
filename = quote(filename)
# 指定如何处置内容
attachment['content-disposition'] = f'attachment; filename="{filename}"'
return attachment
# 创建邮件主体对象
email = MIMEMultipart()
# 设置发件人、收件人和主体
email['From'] = Header('你个人的邮箱')
email['To'] = Header('你想要发送给的人1号;你想要发送给的人2号')
email['Subject'] = Header('离职证明文件请查收', 'utf-8')
# 添加邮件正文内容
content = """据德国媒体报道,当地时间9日,德国火车司机工会成员进行了投票,
定于当地时间10日起进行全国性罢工,货运交通方面的罢工已于当地时间10日19时开始。
此后,从11日凌晨2时到13日凌晨2时,德国全国范围内的客运和铁路基础设施将进行48小时的罢工。"""
email.attach(MIMEText(content, 'plain', 'utf-8'))
# 添加一个附件
email.attach(create_attachment('resources', '离职证明.docx'))
# 再添加一个附件
email.attach(create_attachment('resources', '阿里巴巴2020年股票数据.xlsx'))
# 创建SMTP_SSL对象(连接邮件服务器)
# SMTP服务器,由于我使用网易的126邮箱
smtp_obj = smtplib.SMTP_SSL('smtp.126.com', 465)
# 通过用户名和授权码进行登录
smtp_obj.login('个人邮箱', '授权码申请步骤如下')
# 发送邮件(发件人、收件人、邮件内容(字符串))
smtp_obj.sendmail(
'个人邮箱',
['你想要发送给的人1号', '你想要发送给的人2号'],
email.as_string()
)
授权码申请
- 登入邮箱
- POP3/SMTP/IMAP
- POP3/SMTP服务 已关闭 | 开启 (点击开启)
- 扫码申请成功后获得授权码
发送短信
# 通过短信平台发送短信
import random
import requests
def send_message_by_luosimao(tel, message):
"""发送短信(调用螺丝帽短信网关)"""
resp = requests.post(
url='http://sms-api.luosimao.com/v1/send.json',
auth=('api', 'key-20553a237c74f641d7cc3cfd412771a1'),
data={
'mobile': tel,
'message': message
},
timeout=10,
verify=False
)
return resp.json()
def gen_mobile_code(length=6):
"""生成指定长度的手机验证码"""
return ''.join(random.choices('0123456789', k=length))
def main():
code = gen_mobile_code()
message = f'您的短信验证码是{code},打死也不能告诉别人哟!【python课程】'
print(send_message_by_luosimao('手机号', message))
if __name__ == '__main__':
main()
urn ‘’.join(random.choices(‘0123456789’, k=length))
def main():
code = gen_mobile_code()
message = f’您的短信验证码是{code},打死也不能告诉别人哟!【python课程】’
print(send_message_by_luosimao(‘手机号’, message))
if name == ‘main’:
main()