python实现自动发送邮件

自动发送邮件功能是我们经常要用到的,比如每天定时统计报表信息,然后自动发送给运营人员,协助运营人员进行业务数据分析。本文是用Python写的一个自动发送邮件的脚本,调用函数时,直接把发件人邮箱地址、密码、收件人邮箱地址、邮件标题、内容等信息传递给函数,即可实现自动发送邮件功能。

脚本代码如下:

# -*- coding: UTF-8 -*- 
import sys, os, re, urllib, urlparse 
import smtplib 
import traceback 
from email.mime.text import MIMEText 
from email.mime.multipart import MIMEMultipart 
 
def sendmail(subject,msg,toaddrs,fromaddr,smtpaddr,password): 
 ''''' 
 @subject:邮件主题 
 @msg:邮件内容 
 @toaddrs:收信人的邮箱地址 
 @fromaddr:发信人的邮箱地址 
 @smtpaddr:smtp服务地址,可以在邮箱看,比如163邮箱为smtp.163.com 
 @password:发信人的邮箱密码 
 ''' 
 mail_msg = MIMEMultipart() 
 if not isinstance(subject,unicode): 
  subject = unicode(subject, 'utf-8') 
 mail_msg['Subject'] = subject 
 mail_msg['From'] =fromaddr 
 mail_msg['To'] = ','.join(toaddrs) 
 mail_msg.attach(MIMEText(msg, 'html', 'utf-8')) 
 try: 
  s = smtplib.SMTP() 
  s.connect(smtpaddr) #连接smtp服务器 
  s.login(fromaddr,password) #登录邮箱 
  s.sendmail(fromaddr, toaddrs, mail_msg.as_string()) #发送邮件 
  s.quit() 
 except Exception,e: 
  print "Error: unable to send email" 
  print traceback.format_exc() 
 
if __name__ == '__main__': 
 fromaddr = "xxxxxxxx@163.com" 
 smtpaddr = "smtp.163.com" 
 toaddrs = ["xxxxxxxx@qq.com","xxxxxxxxx@163.com"] 
 subject = "测试邮件" 
 password = "xxxxxxxx" 
 msg = "测试一下" 
 sendmail(subject,msg,toaddrs,fromaddr,smtpaddr,password)

相关推荐