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 = "[email protected]" smtpaddr = "smtp.163.com" toaddrs = ["[email protected]","[email protected]"] subject = "测试邮件" password = "xxxxxxxx" msg = "测试一下" sendmail(subject,msg,toaddrs,fromaddr,smtpaddr,password)
相关推荐
一叶不知秋 2020-07-09
Ericbig 2020-05-30
千锋 2020-05-13
Sophisticated 2020-05-09
wklken的笔记 2019-12-25
xiaoxiaoniaoer 2019-12-07
zluxingzhe 2019-12-01
JFEE 2019-04-16
xiaogeldx 2011-09-07
程松 2019-06-30
小方哥哥 2019-06-30
zhongranxu 2019-06-27
idning 2019-04-08
Cowry 2019-03-13
tmaczt 2019-02-20
Dandelionlcp 2019-04-30
huang00 2017-04-26