Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

A case study of Python Group email

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, I would like to share with you the relevant knowledge points of Python mass email case analysis. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

Background

Imagine that now you have a Word invitation template, and then you have a customer list with the customer's name, contact information, email and other basic information, and your boss now needs to replace the name in the invitation template, then generate the Word invitation template into Pdf format, then edit the unified invitation conversation (email body), and then send the invitation attachment to the customer's mailbox in turn.

Under normal circumstances, we must copy and paste the customer name in the Excel form, then replace the Word document one by one, then convert the Word to Pdf format, then copy the mailbox in the Excel form to send the edited email is normal, and then attach the invitation attachment, click on send, about calculate, in the passionate state, this process is fast, it will take about 1 minute or more. If there are only a few dozen customers, it can be done in an hour. What if there are hundreds, thousands, or even tens of thousands of customers? That's probably going to be crying and passing out in the office.

But don't panic, Python Automation Office, a combination of punches, using Python Automation Office-Word document replacement, Excel table reading, Pdf file generation and Email automatic email one-stop service arrangement, let's take a look!

Realization process

1) replace the Word template to generate the corresponding invitation

Here take the above Word template as an example, write a function to replace the customer name in the template, one step at a time.

Def get_invitation (name): doc = docx.Document ("template.docx") for para in doc.paragraphs: if''in para.text: for run in para.runs: if''in run.text: runrun.text = run.text.replace (', name) doc.save (fanci./ invitation / {name} .docx')

The above code needs to understand the structure of Word documents, a document has multiple paragraphs, access with doc.paragraphs; paragraph of the text with para.text access; a paragraph may have multiple different styles of text, these different styles are called run, a paragraph contains multiple run, access with para.runs, a run of the specific text obtained with run.text. Understand these, and then look at the above code, is not much clearer?

2) convert the Word invitation to Pdf format

This is much simpler, Python automation office, one line of code can be achieved, and the speed is also very fast.

From docx2pdf import convert convert (f ". / invitation / {name} .docx")

Use the convert () function to convert a file in docx format into an Pdf document with the same name.

3) read the name and mailbox in the Excel table

We need to use the openpyxl library here. Of course, there are still many libraries about Excel. Here we take this library as an example. The code is as follows:

Def get_username_email (): workbook = openpyxl.load_workbook ("names.xlsx") worksheet = workbook.active for index, row in enumerate (worksheet.rows): if index > 0: name = row [0] .value # get the name of the first column of the table email = row [3] .value # get the mailbox of the fourth column of the table # print (name Email) # print (f "{name} invitation is being generated...") # get_invitation (name) send_email (name, email)

The above code, which should not be difficult to understand, reads the name and mailbox in Excel, then passes it to get_invitation () to generate the invitation, and then passes it to the send_email () function to send the message automatically. In fact, the two parts are carried out separately. Here, the get_invitation () function is executed first, the invitation letter is formed, and then the function is commented out, and then the sending mail function is executed.

4) send mail automatically

With regard to automatic email sending, several historical articles have been published and continue to be used here. At first, I found it very difficult, but later I found it was not as complicated as I thought. The code is as follows:

Smtp = smtplib.SMTP (host= "smtp.qq.com", port=587) # smtp.login (mailbox, authorization code) smtp.login ('235977 authorization qq.compositions, "ruybefkipoo") def send_email (name, email): msg = MIMEMultipart () msg ["subject"] = f "Hello, {name}, your invitation!" Msg ["from"] = "2352180977@qq.com" msg ["to"] = email html_content = f "

Hello: {name}

Welcome to join the Python Advanced Learning Exchange Group. Please check your ticket in the attachment.

Click here to learn more: concert home page

"" html_part = MIMEText (html_content, "html") msg.attach (html_part) with open (f ". / invitation / {name} .pdf", "rb") as f: doc_part = MIMEApplication (f.read ()) doc_part.add_header ("Content-Disposition", "attachment") Filename=name) # add attachments to the message msg.attach (doc_part) # send the previously prepared email smtp.send_message (msg) # if you log in outside There is no need to exit the server connection here, so # smtp.quit () is commented out.

There are three points to pay attention to here: first, mailbox login is placed outside the function to prevent multiple function calls, and multiple login requests for a short period of time are blocked; second, mailbox login uses an authorization code, not your mailbox login password. QQ Mail is used here as an example, and other mailboxes need to change the smtp service. Third, this code not only quotes html writing in the text, but also carries an invitation attachment in Pdf format, which is slightly complicated.

5) complete code

The above four steps are split, and the tasks of Word document replacement, Excel table reading, Pdf file generation and Email automatic mail sending are completed in turn, with the complete code attached here.

Import docx from docx2pdf import convert import openpyxl import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication # generate the corresponding invitation letter And dump the pdf format def get_invitation (name): doc = docx.Document ("template.docx") for para in doc.paragraphs: if''in para.text: for run in para.runs: if''in run.text: runrun.text = run.text.replace ('' Name) doc.save (frank./ invitation / {name} .docx') convert (f ". / invitation / {name} .docx") smtp = smtplib.SMTP (host= "smtp.qq.com", port=587) smtp.login ('235977 invitation qq.compose, "ruybefkipoo") def send_email (name, email): msg = MIMEMultipart () msg ["subject"] = f "Hello" {name}, your invitation! " Msg ["from"] = "2352180977@qq.com" msg ["to"] = email html_content = f "

Hello: {name} Welcome to join the Python Advanced Learning Exchange Group, please check your tickets in the attachment ~ Click here to learn more: concert home page

"" html_part = MIMEText (html_content, "html") msg.attach (html_part) with open (f ". / invitation / {name} .pdf", "rb") as f: doc_part = MIMEApplication (f.read ()) doc_part.add_header ("Content-Disposition", "attachment") Filename=name) # add attachments to the message msg.attach (doc_part) # send the previously prepared email smtp.send_message (msg) # if you log in outside You don't have to exit the server connection here. So comment out # smtp.quit () def get_username_email (): workbook = openpyxl.load_workbook ("names.xlsx") worksheet = workbook.active for index, row in enumerate (worksheet.rows): if index > 0: name = row [0] .value email = row [3] .value # print (name Email) # print (f "{name} invitation is being generated...") # get_invitation (name) send_email (name, email) if _ _ name__ = ='_ main__': get_username_email () # get_invitation ('Python Advanced') these are all the contents of the article "Python Group email case study" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report