在python中怎么生成html格式的邮件并发送

这篇博客介绍了如何在Python中生成HTML格式的邮件,并使用Envelopes模块进行发送。内容包括邮件的HTML结构、CSS应用以及最佳实践,特别强调了在电子邮件中内联样式的重要性,以确保在各种邮件客户端的兼容性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Requirement:

Using CSS with html.HTML():

pypi上的例子就讲的很详细,我就不复述了,下面讲一下如何在邮件中使用CSS。
邮件客户端不支持外部样式,所以我们主要使用内部样式和内联样式。

  • 内部引用CSS样式
from html import HTML
css = """
        .class1 {
            color: #00FF00;
        }
        .class2 {
            color: #FF0000;
        }
        .class3 {
            color: #FFFF00;
        }
    """

h = HTML('head')
h.text('<style>{}</style>'.format(css), escape=False)
b = HTML('body')
t = b.table(border='1')
r = t.tr()
r.td('column 1', klass='class1')
r.td('column 2', klass='class2')
r.td('column 3', klass='class3')
print '{} {}'.format(h,b)
  • 内联引用CSS样式 (有些邮件客户端会忽略里面的样式,所以推荐使用内联样式)
from html import HTML
inline_css={
           'class1':'color:#00FF00;',
           'class2':'color:#FF0000;',
           'class3':'color:#FFFF00;',
}

b = HTML()
t = b.table(border='1')
r = t.tr()
r.td('column 1', style=inline_css['class1'])
r.td('column 2', style=inline_css['class2'])
r.td('column 3', style=inline_css['class3'])
print str(b)

发邮件

Envelopes的例子已经很清楚了。

<think>我们已经在之前的回答中提供了发送纯文本邮件的示例。现在用户要求发送HTML格式邮件,我们需要修改邮件正文部分,使用MIMEText指定类型为'html',同确保邮件内容符合HTML格式。 ###解决方案1.**创建HTML格式邮件正文**:使用`MIMEText`对象,将`_subtype`设置为`'html'`。 2. **构建HTML内容**:邮件正文字符串需要包含有效的HTML标签(如`<html>`, `<body>`等)。3.**其他部分不变**:包括附件、抄送等处理方式与纯文本邮件相同。 ###示例代码以下是在KNIME中使用Python脚本发送HTML格式邮件的完整示例: ```pythonimport smtplibfrom email.mime.multipartimport MIMEMultipartfromemail.mime.textimport MIMETextfrom email.mime.base importMIMEBasefrom emailimport encodersimport os#邮件基本信息(可以通过KNIME变量传入)sender_email= "your_email@gmail.com" receiver_emails= ["recipient1@example.com", "recipient2@example.com"]cc_emails= ["cc1@example.com","cc2@example.com"] subject= "AutomatedHTML Reportfrom KNIME"#创建HTML格式邮件正文html_body =""" <html><body><h1>KNIMEAutomated Report</h1><p>This isan <strong>HTML formatted</strong> emailsent fromKNIME.</p><p>Here isa table:</p><tableborder="1"><tr><th>Column1</th><th>Column2</th></tr><tr><td>Data1</td><td>Data2</td></tr></table></body> </html>""" #创建邮件对象msg= MIMEMultipart() msg['From'] =sender_emailmsg['To'] =", ".join(receiver_emails) msg['Cc'] =", ".join(cc_emails) msg['Subject'] =subject#添加HTML正文msg.attach(MIMEText(html_body, 'html'))#添加附件(可选) attachment_paths= ["/path/to/report.pdf"]#替换为实际路径for file_path inattachment_paths:ifos.path.exists(file_path):part= MIMEBase('application', 'octet-stream')withopen(file_path,'rb') asfile:part.set_payload(file.read())encoders.encode_base64(part)filename =os.path.basename(file_path)part.add_header('Content-Disposition',f'attachment;filename="{filename}"')msg.attach(part)#发送邮件try:smtp_server =smtplib.SMTP('smtp.gmail.com',587)smtp_server.starttls()smtp_server.login(sender_email, "your_app_password")#使用应用专用密码all_recipients =receiver_emails+ cc_emailssmtp_server.sendmail(sender_email,all_recipients, msg.as_string())smtp_server.quit()print("Emailsent successfully!") exceptException ase:print(f"Error sendingemail:{e}") ```### KNIME工作流集成建议1.**使用变量传递参数**:在KNIME中,可以通过`FlowVariables`动态设置发件人、收件人列表、主题、附件路径等参数,避免硬编码。 2. **错误处理**:在Python脚本中捕获异常打印错误信息,便于在KNIME中查看执行日志。 3. **HTML内容生成**:可以在KNIME中使用`StringManipulation`节点或`TabletoHTML`节点生成HTML内容,再通过变量传递给Python脚本。 ###注意事项-**HTML格式验证**:确保HTML内容正确无误,否则邮件客户端可能无法正常渲染。- **安全认证**:对于Gmail等邮箱,可能需要启用“允许不够安全的应用”或使用应用专用密码。- **附件路径**:确保KNIME工作流有权限读取附件文件,路径可以是绝对路径或相对于工作流的路径。---###相关问题1.如何在KNIME中动态生成HTML邮件内容?2.发送HTML邮件如何嵌入图片(而非附件)? 3.如何设置邮件优先级和请求已读回执?4.在KNIME中使用Python发送邮件如何避免被识别为垃圾邮件?</think>### 在KNIME中使用Python发送HTML格式邮件 以下是实现HTML格式邮件发送的完整方案,基于Python的`email`和`smtplib`库: #### 核心步骤 1. **创建MIMEMultipart对象**:作为邮件容器 2. **添加HTML正文**:使用`MIMEText`指定`subtype='html'` 3. **处理附件**:使用`MIMEApplication`或`MIMEBase` 4. **SMTP连接**:通过安全连接发送 #### 完整代码示例 ```python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.application import MIMEApplication import os # 配置参数(建议通过KNIME变量传入) SMTP_SERVER = "smtp.gmail.com" SMTP_PORT = 587 SENDER_EMAIL = "your_email@gmail.com" SENDER_PASSWORD = "your_app_password" # 建议使用应用专用密码 RECIPIENTS = ["user1@example.com", "user2@example.com"] CC_RECIPIENTS = ["manager@example.com", "team@example.com"] SUBJECT = "KNIME自动化报告" ATTACHMENT_PATHS = ["/reports/daily_report.html", "/data/summary.xlsx"] # 创建HTML邮件内容 html_content = """ <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; } .header { background-color: #f0f0f0; padding: 10px; } .content { margin: 20px; } table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #ddd; padding: 8px; } th { background-color: #4CAF50; color: white; } </style> </head> <body> <div class="header"> <h1>每日数据分析报告</h1> <p>生成间:2023-06-15</p> </div> <div class="content"> <h2>关键指标</h2> <table> <tr> <th>指标</th> <th>今日值</th> <th>变化率</th> </tr> <tr> <td>用户活跃度</td> <td>24,567</td> <td>+12.5%</td> </tr> <tr> <td>转化率</td> <td>8.7%</td> <td>+2.3%</td> </tr> </table> <h2>可视化图表</h2> <img src="cid:chart1" alt="销售趋势图" width="600"> <p>更多详情请查看附件报告</p> </div> </body> </html> """ # 创建邮件对象 msg = MIMEMultipart() msg['From'] = SENDER_EMAIL msg['To'] = ", ".join(RECIPIENTS) msg['Cc'] = ", ".join(CC_RECIPIENTS) msg['Subject'] = SUBJECT # 添加HTML正文 msg.attach(MIMEText(html_content, 'html')) # 添加附件 for file_path in ATTACHMENT_PATHS: if os.path.exists(file_path): with open(file_path, "rb") as attachment: part = MIMEApplication( attachment.read(), Name=os.path.basename(file_path) ) part['Content-Disposition'] = f'attachment; filename="{os.path.basename(file_path)}"' msg.attach(part) # 发送邮件 try: with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server: server.starttls() server.login(SENDER_EMAIL, SENDER_PASSWORD) all_recipients = RECIPIENTS + CC_RECIPIENTS server.sendmail(SENDER_EMAIL, all_recipients, msg.as_string()) print("HTML邮件发送成功") except Exception as e: print(f"发送失败: {str(e)}") ``` #### 关键特性说明 1. **HTML格式支持**: - 使用`MIMEText(html_content, 'html')`指定HTML类型 - 支持完整的HTML/CSS样式和表格布局 - 可嵌入动态生成的图表(需使用`cid:`引用) 2. **多附件处理**: - 自动读取本地文件附加 - 支持任意文件类型(PDF, Excel, 图片等) - 保留原始文件名 3. **安全连接**: - 使用`starttls()`加密传输 - 建议使用应用专用密码而非账户密码[^3] #### KNIME集成建议 1. **参数动态化**: ```python # 在KNIME Python节点中接收变量 recipient_var = flow_variables['recipient_list'] subject_var = flow_variables['email_subject'] ``` 2. **HTML内容生成**: - 使用KNIME的`Table to HTML`节点转换数据 - 通过`String Manipulation`构建动态HTML 3. **错误处理**: - 添加`try/except`块捕获SMTP异常 - 返回状态信息到KNIME工作流 #### 注意事项 1. Gmail需开启"允许不够安全的应用"或使用OAuth2认证 2. 附件总大小通常限制在25MB以内 3. HTML中的外部资源可能被邮件客户端阻止 4. 使用CSS内联样式提高兼容性 > 通过组合KNIME的数据处理能力和Python邮件功能,可实现高度自动化的报告分发系统。例如将Matplotlib图表[^2]或Processing.js可视化[^1]结果嵌入邮件发送。 --- ### 相关问题 1. 如何在HTML邮件中嵌入动态生成的图表? 2. 使用KNIME变量动态控制邮件内容的最佳实践是什么? 3. 如何通过OAuth2认证提高邮件发送安全性? 4. 邮件附件大小超出限制应如何分割处理?
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值