python_实现发送邮件功能

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib

def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr(( Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr))

from_addr = 'xxx@xxx.com'
#from_addr = 'service@xxx.com'
#password = "xxx"
password = 'xxx'
to_addr = 'xxx@demo.com'
smtp_server = 'mail.xxx.com' 

html_content = '''
<table border="1">
<tr>
<td>字段名</td>
<td>uri标识</td>
</tr>
<tr>
<td>字段名</td>
<td>uri标识</td>
</tr>
</table>
'''
msg = MIMEText(html_content, 'html', 'utf-8')
msg['From'] = _format_addr(u'iTitle <%s>' % from_addr)
msg['To'] = _format_addr(u'管理员 <%s>' % to_addr)
msg['Subject'] = Header(u'邮件标题', 'utf-8').encode()

server = smtplib.SMTP(smtp_server, 587)
server.set_debuglevel(1)
# server.login(from_addr, password)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()

posted @ 2017-04-13 22:48  ZhangRuoxu  阅读(349)  评论(0编辑  收藏  举报