个性化推荐 python

    科技2023-12-01  97

    个性化推荐 python

    Sometimes, we might be in a situation where we have to send emails to multiple people in a personalised manner (like mailing each student their grades, mailing bank statements to customers, etc.). Although these emails follow the same format, the information inside it varies from receiver to receiver. When done manually, it is time-consuming and there is a lot of room for error. Python allows us to automate this process very easily, let’s see how it’s done.

    有时,我们可能处在必须以个性化方式向多个人发送电子邮件的情况下(例如,向每个学生邮寄其成绩,向客户邮寄银行对帐单等)。 尽管这些电子邮件采用相同的格式,但其中的信息因收件人而异。 手动完成时,这很耗时,并且有很大的出错空间。 Python使我们可以非常轻松地自动执行此过程,让我们看看它是如何完成的。

    For this, you will need:

    为此,您将需要:

    1.A Gmail account for development

    1.一个用于开发的Gmail帐户

    2. template.txt file — containing the format for the email body

    2. template.txt文件-包含电子邮件正文的格式

    3. details.csv file — CSV file containing details of the recipients

    3. details.csv文件-包含收件人详细信息的CSV文件

    4. app.py — the python script

    4. app.py-python脚本

    1. Gmail帐户进行开发 (1. Gmail account for development)

    As the python script will access the Gmail account the send out emails, we need to turn Allow less secure apps to ON in that account. This makes it easier for others to gain access to your account. Hence it is recommended to set up a dummy account/temporary account for this purpose.

    由于python脚本将访问Gmail帐户发送电子邮件,我们需要把 允许不够安全的应用为ON 该帐户。 这使其他人更容易访问您的帐户。 因此,建议为此目的设置一个虚拟帐户/临时帐户。

    2. template.txt文件 (2. template.txt file)

    This text file contains the format for the email body. The personal details from the details.csv file are each placed in the placeholder defined by ‘${}’ in this text file.

    此文本文件包含电子邮件正文的格式。 来自details.csv文件的个人详细信息均放置在此文本文件中由“ $ {}”定义的占位符中。

    Dear ${PERSON_NAME},You have secured the following marks in your mid-term exams:Math - ${MATH}English - ${ENG}Science - ${SCI}

    3. details.csv文件 (3. details.csv file)

    The details.csv/details.xlsx file contains the details that must populate the placeholders in the template file. It contains the details that must be sent to the recipients.it can be an excel file or CSV file.

    details.csv / details.xlsx文件包含必须填充模板文件中占位符的详细信息。 它包含必须发送给收件人的详细信息。它可以是excel文件或CSV文件。

    Here is an example of the details file — contains the student details of the marks they secured in their midterm exams in each subject. 这是详细信息文件的示例-包含学生在每个学科的期中考试中获得的分数的学生详细信息。

    4. python脚本 (4. The python script)

    After we have the CSV file and the template file ready, it is now time to write the python script.

    准备好CSV文件和模板文件后,现在该编写python脚本了。

    一世。 导入必要的模块 (i. Import the necessary modules)

    import smtplibimport csvfrom string import Templatefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMEText

    ii。 读取template.txt文件的功能 (ii. Function to read the template.txt file)

    This function returns the template object containing the contents of the template.txt file.

    此函数返回包含template.txt文件内容的模板对象。

    def read_template(filename): with open(filename, ‘r’, encoding=’utf-8') as template_file: template_file_content = template_file.read() return Template(template_file_content)

    iii。 设置SMTP服务器 (iii. Set up the SMTP server)

    Next, we set up an SMTP connection with the Gmail account using .starttls().

    接下来,我们使用.starttls()与Gmail帐户建立SMTP连接。

    Its isn’t a good practice to include the account address, password in the script if you are going to share this script with others. Instead, use input() to let the user type in their password when running the script.

    如果要与他人共享此脚本,则在脚本中包含帐户地址和密码不是一个好习惯。 而是使用input()让用户在运行脚本时输入密码。

    MY_ADDRESS = *********@gmail.com #your gmail account address PASSWORD = *********** #your password s = smtplib.SMTP(host=’smtp.gmail.com’, port=587) s.starttls() s.login(MY_ADDRESS, PASSWORD)

    iv。 构造电子邮件正文 (iv. Construct the email body)

    Loop through the CSV file and create a message for each row in the CSV file.

    循环浏览CSV文件,并为CSV文件中的每一行创建一条消息。

    Create a message using MIMEMultipart() function, substitute the details (from each row) in the template to form the message body and save it to the message variable.

    使用MIMEMultipart()函数创建消息,替换模板中的详细信息(来自每一行)以形成消息正文并将其保存到message变量中 。

    Next, set up the parameters such as from and to address, message subject. Attach the message variable to the message body.

    接下来,设置参数,例如从和到地址,邮件主题。 将message变量附加到消息正文。

    At last, send the message via the send_message() function.

    最后,通过send_message()函数发送消息。 # read the message templatemessage_template = read_template(‘template.txt’)with open(“details.csv”, “r”) as csv_file: csv_reader = csv.reader(csv_file, delimiter=’,’) # skip the first row as it is the header next(csv_reader) for row in csv_reader: msg = MIMEMultipart() # create a message# add in the actual person name to the message template message= message_template.substitute(PERSON_NAME=row[0],MATH=row[2], ENG=row[3],SCI=row[4]) # Prints out the message body for our sake print(message)# setup the parameters of the message msg[‘From’]=MY_ADDRESS msg[‘To’]=lines[1] msg[‘Subject’]=”Mid term grades”# add in the message body msg.attach(MIMEText(message, ‘plain’))# send the message via the server set up earlier. s.send_message(msg) del msg# Terminate the SMTP session and close the connections.quit()

    Finally, do not forget to close the SMTP connection after sending all the messages.

    最后,不要忘了在发送所有邮件后关闭SMTP连接。

    最终代码 (The final code)

    import smtplibimport csvfrom string import Templatefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextdef read_template(filename): with open(filename, ‘r’, encoding=’utf-8') as template_file: template_file_content = template_file.read() return Template(template_file_content)def main(): message_template = read_template(‘template.txt’)MY_ADDRESS = ‘**********@gmail.com’ PASSWORD = ‘*************’# set up the SMTP server s = smtplib.SMTP(host=’smtp.gmail.com’, port=587) s.starttls() s.login(MY_ADDRESS, PASSWORD) with open(“details.csv”, “r”) as csv_file: csv_reader = csv.reader(csv_file, delimiter=’,’) # the below statement will skip the first row next(csv_reader) for lines in csv_reader: msg = MIMEMultipart() # create a message# add in the actual person name to the message template message = message_template.substitute(PERSON_NAME=row[0],MATH=row[2], ENG=row[3],SCI=row[4]) print(message)# setup the parameters of the message msg[‘From’]=MY_ADDRESS msg[‘To’]=lines[1] msg[‘Subject’]=”Mid term grades”# add in the message body msg.attach(MIMEText(message, ‘plain’))# send the message via the server set up earlier. s.send_message(msg) del msg # Terminate the SMTP session and close the connection s.quit()if __name__ == ‘__main__’: main()

    There you have it! Now you can send a lot of emails with personal details within a few seconds.

    你有它! 现在,您可以在几秒钟内发送许多包含个人详细信息的电子邮件。

    翻译自: https://medium.com/swlh/python-automation-how-to-send-personalised-emails-with-python-b6113a6eba03

    个性化推荐 python

    相关资源:Project1_GUI_Python_Automation_Test:Hulb的采访-源码
    Processed: 0.013, SQL: 8