安装第三方库 python-docx
官方链接:https://python-docx.readthedocs.io/en/latest/
pip install python-docx
如果需要处理图片,需要安装pillow
pip install pillow
表格样式模板:https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html
文档的结构如下:
document对象下面有多个paragraphs对象,paragraphs对象下面有多个run对象
doc = Document()
run = doc.paragraphs[0].runs[1]
表格结构是:
tables -row -cell - paragraph
示例代码如下:
from docx import Document
from docx.shared import Cm, Pt
from docx.document import Document as Doc
from docx.oxml.ns import qn
# 新建一个word对象
document = Document() # type:Doc
# 添加标题,0表示最顶级的标题
document.add_heading('Document Title', 0)
# 添加一个段落
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True # 加粗
p.add_run(' and some ') # add_run方法在段落后加短文字
p.add_run('italic.').italic = True # 斜体
run = p.add_run("加大的字。I love you")
run.font.size = Pt(18)
run.font.name = "Arial" # 设置西文字体
run._element.rPr.rFonts.set(qn('w:eastAsia'), '微软雅黑') # 设置中文字体
# 添加一个1级标题
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(
'first item in ordered list', style='List Number'
)
# 添加一个图片,指定宽度
document.add_picture('resources/dandan.jpg', width=Cm(6))
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)
# 添加表格
table = document.add_table(rows=1, cols=3)
table.style = "Colorful Grid"
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for qty, id, desc in records:
row_cells = table.add_row().cells
row_cells[0].text = str(qty)
row_cells[1].text = id
row_cells[2].text = desc
# 添加一个空白页
document.add_page_break()
# 保存
document.save('resources/demo.docx')
练习:替换文档内容,批量生成离职证明
from docx import Document
from docx.document import Document as Doc
employees =[
{
"name": "Alice", "date": "2023年3月22日"
},
{
"name": "Bob", "date": "2023年3月16日"
}
]
for employee in employees:
doc = Document("resources/离职证明模板.docx") # type:Doc
for p in doc.paragraphs:
print(p.text)
for key, value in employee.items():
if key in p.text:
print(f"{key}--->{value}")
p.text = p.text.replace(key, value)
doc.save(f"resources/离职证明{employee['name']}.docx")
发送邮件
首先去获取QQ的授权码,在设置-账户里,点击生成授权码。
参考了这里,他这里比较全,我下面这个只写了常用的发送html格式邮件:https://www.cnblogs.com/rainbow-tan/p/16848236.html
import datetime
import smtplib
from email.mime.text import MIMEText
import time
# 创建smtp对象
smtp_obj = smtplib.SMTP_SSL("smtp.qq.com", 465)
# 登录
smtp_obj.login("hanayo@kayotin.cn", "xxxxxxx")
body = f"""
测试Python发送邮件【正文】
<H1>今天是 {datetime.datetime.today().strftime("%Y年%m月%d日")}</H1>
<H2>现在的时间是 {time.strftime('%H:%M:%S', time.localtime())}</H2>
<p style="color: green;">测试正文完毕~~~~</p>
"""
# 创建一封文本邮件对象
email = MIMEText(body, "html")
sender = "hanayo@kayotin.cn"
email["Subject"] = "python发送html格式邮件3" # 邮件主题
email["From"] = "hanayo@kayotin.cn" # 发送者的显示名称
to_mail = ["ahjiang@capvision.com"]
email["To"] = ",".join(to_mail) # 收件人的显示名称
cc_mail = ["18237763193@163.com", "ahjiang@capvision.com"]
email["Cc"] = ",".join(cc_mail) # 抄送的显示名
# 以上只是显示,但要和实际一致,否则会被认为是垃圾邮件
# 发送, 发件人,收件人和cc,邮件内容
smtp_obj.sendmail(sender, to_mail+cc_mail, email.as_string())
smtp_obj.quit()
Python发送邮件(O365
O365用的是tsl,端口是587,连接方式需要修改下。
import datetime
import smtplib
from email.mime.text import MIMEText
import time
user_name = "xxxx@capvision.com" # 登录账号
password = "xxx" # 密码
sender = "ahjiang@capvision.com" # 实际的发件人
smtp_conf ={
"host": "smtp.partner.outlook.cn",
"password": password,
"port": 587,
"tls": True
}
def create_email(mail_title, mail_body, mail_type, mail_to, mail_cc):
"""
创建一个邮件对象
:param mail_title:邮件标题,str
:param mail_body: 邮件正文,html写的字符串
:param mail_type: 邮件类型,建议html
:param mail_to: 收件人,List
:param mail_cc: 抄送,List
:return: 返回一个邮件对象
"""
email_obj = MIMEText(mail_body, mail_type) # 新建一个邮件对象
email_obj["Subject"] = mail_title # 邮件主题
email_obj["From"] = sender # 发送者的显示名称
email_obj["To"] = ",".join(mail_to) # 收件人的显示名称
email_obj["Cc"] = ",".join(mail_cc) # 抄送的显示名
return email_obj
def send_by_o365(mail_to, mail_cc, mail_obj):
"""
发送邮件
:param mail_to:收件人,列表
:param mail_cc: 抄送人,列表
:param mail_obj: 邮件对象
:return: 发送成功返回True
"""
mail_server = smtplib.SMTP(smtp_conf["host"], smtp_conf["port"])
mail_server.ehlo()
mail_server.starttls()
mail_server.login(user_name, password)
mail_server.sendmail(sender, mail_to + mail_cc, mail_obj.as_string())
mail_server.quit()
return True
if __name__ == '__main__':
# 用html写入邮件内容,body是邮件正文
body = f"""
测试Python发送邮件【正文】
<H1>今天是 {datetime.datetime.today().strftime("%Y年%m月%d日")}</H1>
<H2>现在的时间是 {time.strftime('%H:%M:%S', time.localtime())}</H2>
<p style="color: green;">测试正文完毕~~~~</p>
"""
title = "用python发送邮件" # 标题
to_mail = ["hanayo@kayotin.cn"] # 收件人,列表
cc_mail = ["18237763193@163.com", "ahjiang@capvision.com"] # 抄送,列表
type_mail = "html" # 邮件类型,一般是html
# 创建一封html邮件对象
new_email = create_email(title, body, type_mail, to_mail, cc_mail)
# 发送邮件
send_by_o365(to_mail, cc_mail, new_email)