python 邮件发送实例
#!/usr/bin/env python # -*- coding: utf-8 -*- from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import smtplib import time _from_addr = "XXX@XXX.com" # 自定义发送邮箱 _password = "XXXXXX" # 发送邮箱登录密码 _to_addr = [_from_addr] # 自定义默认收件人列表 _smtp_server = "smtp.exmail.qq.com" # SMTP服务器,本实例使用企业QQ邮箱 def _format_addr(s): """ 格式化一个邮件地址 :param s: :return: """ name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr)) def send_mail(to_list=_to_addr, sub="邮件功能调试默认主题", content="邮件功能调试默认邮件内容"): """ to_list:收件人列表;sub:主题;content:邮件内容 """ msg = MIMEText(content, _subtype='html', _charset='utf-8') # 创建一个实例,这里设置为html格式邮件 msg['From'] = _format_addr(u'4399PTQA <%s>' % _from_addr) msg['To'] = _format_addr(",".join(to_list)) msg['Subject'] = Header(sub, 'utf-8').encode() # 设置主题 try: server = smtplib.SMTP(_smtp_server, 25) # server.set_debuglevel(1) server.login(_from_addr, _password) server.sendmail(_from_addr, to_list, msg.as_string()) server.quit() return True except Exception, e: print(str(e)) return False if __name__ == '__main__': title = "PTQA测试报告:" + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 邮件主题 msg = """<html> <body> <h1>Hello</h1> <p>send by <a href="http://www.cnblogs.com/guanfuchang">Milton</a>...</p>' </body></html>""" to_addr = ["guan825@126.com"] if send_mail(to_list=to_addr, sub=title, content=msg): print("发送成功") else: print("发送失败")