使用python发送html的邮件

实现功能1:查询数据,然后做成报表,再发送这些报表

 

代码:

写道
import smtplib
from datetime import datetime, timedelta
import time
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart

def get_html_msg(send_date):
     head = """<head><meta charset="utf-8">
    <STYLE TYPE="text/css" MEDIA=screen>
    <!--
     table {font-size:20px;border-collapse: collapse;font-family: arial;}
    thead {border: 2px solid #B1CDE3;background: #00ffff;font-size:18px;padding: 10px 10px 10px       10px;color: #4f6b72;font-family: times;}
     th {vertical-align:top;font-size:12px;padding: 5px 5px 5px 5px;color: #4f6b72;font-family: arial;}
     body {font-family: arial;}
    -->
    </STYLE>
    </head>"""

     p = """<p>大家好:<br>截止到 """ + get_cpu_report_date(send_date, format_min) + """,各个设备性     能指标报表如下,请查阅。<br></p>"""

     body = """<body>""" + p + """
     <table border="0" cellpadding="0" cellspacing="0">
     <th>""" + get_cpu_table() +"""</th>
     <th>"""+get_io_table() + """</th>
     <th>"""+get_load_table() + """</th>
     <th>"""+get_memory_table() + """</th>
     <th>"""+get_process_speed_table() + """</th>
     </table>
     </body>"""
     html = """<html>""" + head + body + """</html>"""
     return html

def send_mail(html_msg):
     msg = MIMEMultipart()
     content = MIMEText(html_msg,'html')
     msg.attach(content)
     msg['To'] = ";".join(to_list)
     msg['From'] = from_addr
     msg['Subject'] = subject
     s = smtplib.SMTP('xxxx')
     s.set_debuglevel(0)
     s.sendmail(from_addr, to_list, msg.as_string())
     s.quit()
     print "ok"

if __name__ == "__main__":
     now = datetime.now()
     html = get_html_msg()
     send_mail(html)

 

实现功能2(发送附件):(转载)

 

 #!/usr/bin/env python 
#-*-coding:utf8-*- 

import os, smtplib, mimetypes 
from email.mime.text import MIMEText 
from email.mime.image import MIMEImage 
from email.mime.multipart import MIMEMultipart 

MAIL_LIST = ["username@51cto.com"] 
MAIL_HOST = "smtp.51cto.com"
MAIL_USER = "username"
MAIL_PASS = "password"
MAIL_POSTFIX = "51cto.com"
MAIL_FROM = MAIL_USER + "<"+MAIL_USER + "@" + MAIL_POSTFIX + ">"

def send_mail(subject, content, filename = None): 
    try: 
        message = MIMEMultipart() 
        message.attach(MIMEText(content)) 
        message["Subject"] = subject 
        message["From"] = MAIL_FROM 
        message["To"] = ";".join(MAIL_LIST) 
        if filename != None and os.path.exists(filename): 
            ctype, encoding = mimetypes.guess_type(filename) 
            if ctype is None or encoding is not None: 
                ctype = "application/octet-stream"
            maintype, subtype = ctype.split("/", 1) 
            attachment = MIMEImage((lambda f: (f.read(), f.close()))(open(filename, "rb"))[0], _subtype = subtype) 
            attachment.add_header("Content-Disposition", "attachment", filename = filename) 
            message.attach(attachment) 

        smtp = smtplib.SMTP() 
        smtp.connect(MAIL_HOST) 
        smtp.login(MAIL_USER, MAIL_PASS) 
        smtp.sendmail(MAIL_FROM, MAIL_LIST, message.as_string()) 
        smtp.quit() 

        return True
    except Exception, errmsg: 
        print "Send mail failed to: %s" % errmsg 
        return False

if __name__ == "__main__": 
    if send_mail("测试信", "我的博客欢迎您/", r"G:\attachment.rar"): 
        print "发送成功!"
    else: 
        print "发送失败!"
 1、首先要理解一个常识(RFC)

RFC(The Request for Comments)是一个关于Internet各种标准的文档,定义了很多的网络协议和数据格式,标准的Internet邮件遵从RFC2822(Internet Message Format)等几个文档,其中RFC822中描述了邮件头(mail headers)的格式。具体文档在Python帮助里都可以查到全文。

2、其次要熟悉Python的几个模块

关于邮件的有email,smtplib等,关于编码的有base64,binascii等,发送邮件的方式就是先根据RFC构造好邮件的各个部分,然后登录到smtp服务器sendmail就可以了。

3、下面贴代码

1使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客# -*- coding: cp936 -*-

2使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客

3使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客from email.Header import Header

4使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客from email.MIMEText import MIMEText

5使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客from email.MIMEMultipart import MIMEMultipart

6使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客import smtplib, datetime

7使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客

8使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客#创建一个带附件的实例

9使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客msg = MIMEMultipart()

10使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客

11使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客#构造附件

12使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客att = MIMEText(open('d:\\tc201.rar', 'rb').read(), 'base64', 'gb2312')

13使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客att["Content-Type"] = 'application/octet-stream'

14使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客att["Content-Disposition"] = 'attachment; filename="tc201.rar"'

15使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客msg.attach(att)

16使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客

17使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客#加邮件头

18使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客msg['to'] = 'zhousl@xxx.com'

19使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客msg['from'] = 'zhousl@xxx.com'

20使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客msg['subject'] = Header('冒烟测试结果 (' + str(datetime.date.today()) + ')', \

21使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客                        'gb2312')

22使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客#发送邮件

23使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客server = smtplib.SMTP('smtp.xxx.com')

24使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客server.sendmail(msg['from'], msg['to'], \

25使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客                 msg.as_string())

26使用python发送带附件的邮件(转) - 阿郎 - 阿郎的博客server.close

4、几个值得注意的地方

1)构造附件时注意采用正确的字符集,这个困惑我好久,开始没有用gb2312,发过去的压缩文件就是坏的;

2)上面的代码中没有包括登录smtp服务器的指令,而Internet上面的smtp服务器一般都是要求认证的,可以通过smtp.login方法进行登陆

3)sendmail方法中的参数to可以是包含多个地址的元组,这样可以发送邮件给多个人了

4)Python2.4以前的版本是不支持gb2312字符集的,要下载安装Python2.4才能跑上面的代码,当然2.4.1肯定会更好一点

 

Python中,你可以使用内置的`smtplib`库和`email`模块来发送HTML格式的邮件。以下是一个简单的步骤指南: 首先,你需要导入必要的模块: ```python import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText ``` 然后创建一个MIMEMultipart对象,同时包含HTML文本和普通的纯文本: ```python msg = MIMEMultipart('alternative') msg['Subject'] = '主题' msg['From'] = '你的邮箱地址' msg['To'] = '收件人的邮箱地址' # 创建HTML部分 html_content = """ <html> <head></head> <body> <p>这是邮件HTML内容</p> </body> </html> """ # 将HTML转成MIMEText对象,设置charset html_part = MIMEText(html_content, 'html', 'utf-8') # 添加HTML部分到MIMEMultipart msg.attach(html_part) ``` 接下来,如果你有附件的话,可以添加到邮件中: ```python # 如果有附件 with open('attachment.pdf', 'rb') as f: attachment = MIMEBase('application', 'octet-stream') attachment.set_payload(f.read()) # 设置附加信息 attachment.add_header('Content-Disposition', 'attachment', filename='attachment.pdf') msg.attach(attachment) ``` 最后,连接到SMTP服务器并发送邮件: ```python smtp_server = 'smtp.example.com' # 根据你的SMTP服务器填写 smtp_port = 587 # 或者465如果需要加密 try: server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() # 开启TLS连接 server.login(msg['From'], '你的密码') # 登录你的邮箱 server.sendmail(msg['From'], [msg['To']], msg.as_string()) # 发送邮件 print("邮件发送") except Exception as e: print(f"发送邮件失败: {str(e)}") finally: server.quit() ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值