python 发邮件 动态html_使用Python构建动态HTML电子邮件内容

本文介绍如何使用Python的smtplib、email.mime.text和Jinja2模板库来创建并发送包含动态HTML内容的电子邮件。示例中,邮件内容是一个由字典数据填充的两列表格,适合用于自动化发送的日程任务。
摘要由CSDN通过智能技术生成

I have a python dictionary that I'd like to send an email with in the form of a two column table, where I have a Title and the two column headers, and the key,value pair of the dictionary populated into the rows.


title

Column 1 Column 2

"Thn dynamic amount of

%column1data%%column2data%

The column1 and column2 data are the key,value pairs from the associated dictionary.

Is there a way to do this in a simple manner? This is an auotmated email being sent out via a cronjob, once a day after populating the data.

Thank you all.

P.S I know nothing about markdown :/

P.S.S I am using Python 2.7

解决方案

Basic Example: (with templating)

#!/usr/bin/env python

from smtplib import SMTP # sending email

from email.mime.text import MIMEText # constructing messages

from jinja2 import Environment # Jinja2 templating

TEMPLATE = """

{{ title }}

Hello World!.

""" # Our HTML Template

# Create a text/html message from a rendered template

msg = MIMEText(

Environment().from_string(TEMPLATE).render(

title='Hello World!'

), "html"

)

subject = "Subject Line"

sender= "root@localhost"

recipient = "root@localhost"

msg['Subject'] = subject

msg['From'] = sender

msg['To'] = recipient

# Send the message via our own local SMTP server.

s = SMTP('localhost')

s.sendmail(sender, [recipient], msg.as_string())

s.quit()

Relevant Documentation:

NB: This assumes you have a valid MTA on your local system.

Note Also: That you may in fact actually want to use a multipart message when composing the email; See Examples

Update: As an aside there are some really nice(er) "email sending" libraries out there that may be of interest to you:

I believe these libraries are along the same lines as requests -- SMTP for Humans

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值