Create Personalized New Year Emails with Python, Jinja2, and Yagmail
Learn how to craft and send customized New Year greeting emails by building HTML templates with Jinja2 placeholders, converting images to base64, and automating delivery using Python's yagmail library, including setup, code snippets, and tips for handling multiple recipients efficiently.
In the previous tutorial we covered simple email sending with yagmail. This article shows how to generate personalized New Year greeting emails by using HTML templates with Jinja2 placeholders and sending them via Python.
1. Preparation
Make sure Python and pip are installed; you can use the detailed Python installation guide or install Anaconda for data‑analysis needs. It is recommended to edit code with VSCode.
Install the required libraries:
pip install jinja2
pip install yagmail2. Write HTML Template
Create an HTML file for the email and embed variables using {{}}. Four key variables are used:
Logo image (base64 encoded)
Background image (URL)
Recipient name
Blessing text
Example snippet for the logo image:
<tr>
<td valign="left" width="50%">
<h1><img src="data:image/png;base64, {{pythondict_img}}"></h1>
</td>
</tr>Background image must be set with a URL to avoid QQ mail filtering:
<td valign="middle" style="background-image: url({{backgroud}});">Recipient name and blessing are inserted as:
<h2>{{name}}<br>祝您2021年元旦快乐</h2>
<p>{{bless}}.</p>3. Python Code
Define a Mail class that logs messages and sends emails using yagmail.SMTP:
class Mail:
"""邮件相关类"""
def log(self, content):
now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"{now_time}: {content}")
def sendmail(self, html, title, receivers):
"""发送邮件
Arguments:
html {str} -- 邮件正文(html)
title {str} -- 邮件标题
receivers {list} -- 邮件接收者,数组
"""
yag = yagmail.SMTP(host='您的邮箱SMTPHOST', user='您的邮箱', password='您的邮箱密码', smtp_ssl=True)
yag.send(receivers, title, html)
self.log("邮件发送成功")Utility to convert an image to base64:
def get_image_base64(path):
"""获得图片的base64编码"""
import base64
f = open(path, "rb")
base64_data = base64.b64encode(f.read())
f.close()
return base64_data.decode("utf-8")Define a dictionary bless_info where each key is a recipient email (or a comma‑separated list) and the value contains the variables for the template:
bless_info = {
"[email protected]": {
"pythondict_img": get_image_base64("./images/pythondict.png"),
"name": "实用宝典",
"background": "https://背景图片.jpg",
"bless": "愿所有的幸运与您不期而遇..",
"title": "祝宝典哥明年粉丝破十万"
},
"[email protected]": {
"pythondict_img": get_image_base64("./images/pythondict.png"),
"name": "老王",
"background": "https://背景图片.jpg",
"bless": "祝您女儿明年考研顺顺利利,全家幸福安康..",
"title": "老王,祝您元旦快乐!"
}
}Render the template and send the email for each entry:
tm = Template(open('./index.html', encoding="utf-8").read())
for mail in bless_info:
msg = tm.render(bless_info[mail])
Mail().sendmail(html=msg, title=bless_info[mail]["title"], receivers=[mail])To send the same email to multiple people, use a comma‑separated key and split it:
bless_info = {
"[email protected],[email protected],[email protected]": {
"pythondict_img": get_image_base64("./images/pythondict.png"),
"name": "老王一家",
"background": "https://背景图片.jpg",
"bless": "祝王小女明年考研顺顺利利,老王全家幸福安康,吉祥如意..",
"title": "老王一家,祝你们元旦快乐!"
}
}
for mail in bless_info:
msg = tm.render(bless_info[mail])
Mail().sendmail(html=msg, title=bless_info[mail]["title"], receivers=mail.split(","))Run the script with: python mail.py After testing, the script will send personalized New Year emails to the specified recipients.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
