程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python office automation

編輯:Python

Send mail to the designated mailbox

  • Send an email to the designated mailbox to send the payroll .docx Send as an attachment

Send an email to the designated mailbox to send the payroll .docx Send as an attachment

Realize the idea :
1、 from excle Read the contents of the file in the table
2、 Will read the data , As a parameter , write in word file , Email address is not written into it
3、 Write the body of the message , Read the attachment
4、 Building links
5、 Send E-mail

#coding:utf-8
import docx, xlrd, glob, smtplib, time
from docx.enum.style import WD_STYLE_TYPE
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT, WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
from docx.enum.table import WD_TABLE_ALIGNMENT
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# Open the workbook
excel = xlrd.open_workbook("salary.xlsx")
# Read sheet page
book = excel.sheet_by_name(" R & D payroll ")
class Email_test(object):
def __init__(self, mail_user, mail_pass, mail_host):
self.mail_user = mail_user
self.mail_pass = mail_pass
self.mail_host = mail_host
resp = self.read_excel()
self.word_style()
self.create_salarg(resp)
self.send_mail(mail_user, mail_pass, mail_host, resp)
def read_excel(self):
# Read table contents by row
content_all = []
for row_value in book.get_rows():
content = []
for cell_value in row_value:
content.append(cell_value.value)
content_all.append(content)
return content_all
doc = docx.Document()
def word_style(self):
# Set font and size and format
style = self.doc.styles['Normal']
style.font.name = " Microsoft YaHei "
style.element.rPr.rFonts.set(qn('w:eastAsia'), u' Microsoft YaHei ')
style.font.size = Pt(11)
# Set the title format and text size
title = self.doc.add_heading("", 0)
title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
_t = title.add_run("5 Monthly payroll ")
_t.font.name = " Microsoft YaHei "
_t.element.rPr.rFonts.set(qn('w:eastAsia'), u' Microsoft YaHei ')
_t.bold = True
# Define payroll mail function
def create_salarg(self,content_all):
# self.word_style()
# Create a two line ,X List of tables
table = self.doc.add_table(rows=2, cols=book.ncols-1, )
# Set the header
title_cells = table.rows[0].cells
for index, salary in enumerate(content_all[0][0:-1]):
title_cells[index].text = salary
# Fill in cells
for data in content_all[1:]:
# Set the number of cells in this line
# add_row: Add a row of data on the basis of the original table
row_cells = table.rows[1].cells
for index, content in enumerate(data[0:-1]):
# Data type conversion , Floating point numbers cannot be written directly to cells , Transform the data
content_to_str = str(content)
row_cells[index].text = content_to_str
self.doc.save("{}5 Monthly payroll .docx".format(data[0]))
# Custom mail sending function
def send_mail(self, mail_user, mail_pass, mail_host, content_all):
sender = '[email protected]' # Sender email
for receiver_name in content_all[1:]:
path = glob.os.path.join(glob.os.getcwd(), '{}5 Monthly payroll .docx'.format(receiver_name[0]))
# Read the attachment contents
attr = MIMEText(open(path, 'rb').read(), 'base64', 'utf-8')
attr['Content-Type'] = 'application/octet-stream'
attr.add_header("Content-Disposition", "attachment", filename=("gbk", "", receiver_name[0] + "5 Monthly payroll .docx"))
message = MIMEMultipart() # Define the mail object
message['From'] = Header(sender)
message['subject'] = Header(' Payroll ') # Email subject
receiver = receiver_name[-1]
# Add attachments to the message
message.attach(attr)
msg_content = """
<p > dear
""" + receiver_name[0] + """
:</p>
<p > Thank you for your contribution to the company !</p>
<p > The salary of this month has arrived , Please remember to check . If not received , Please visit 5 Contact the human resources department within working days .</p>
<p > Please check the email attachment for details of your payroll !</p>
<p > If you have any objection, please contact the human resources department .</p></p>
<br /><br /><br />
<p > Human Resources Department <br />2021 year 5 month 31 Japan </p>
"""
message.attach(MIMEText(msg_content, 'html', 'utf-8'))
try:
# Email protocol
smtobj = smtplib.SMTP()
# Building links ,port The general default is 25
smtobj.connect(mail_host, port)
# Log in to email
smtobj.login(mail_user, mail_pass)
smtobj.sendmail(sender, [receiver], message.as_string())
except smtplib.SMTPException as e:
print("error: %s" % e)
if __name__ == '__main__':
# User login
mail_user = 'xxxx'
# Set personal password
mail_pass = 'xxxxx‘
mail_host = 'x x x x'
Email_test(mail_user, mail_pass, mail_host)

The code needs to be optimized


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved