首页 > 代码库 > Python 发邮件
Python 发邮件
普通邮件
[root@localhost checksalt]# cat python_email.py #!/usr/bin/python # -*- coding: utf-8 -*- import sys def smtp(title,file): import smtplib from email.mime.text import MIMEText from email.header import Header with open(file, ‘r‘) as f: content = f.read() #加邮件头 msg=MIMEText(content,‘plain‘, ‘utf-8‘) to_list=[‘XXX1@qq.com‘,XXX2@qq.com] msg[‘from‘] = ‘XXX@qq.com‘ msg[‘subject‘] = title #发送邮件 try: server = smtplib.SMTP() server.connect(‘smtp.exmail.qq.com‘) server.login(‘XXX@qq.com‘,‘xxxxx‘)#XXX为用户名,xxxxx为密码 server.sendmail(msg[‘from‘],to_list,msg.as_string()) server.quit() print ‘发送成功‘ except Exception, e: print str(e) if __name__ == ‘__main__‘: smtp(sys.argv[1],sys.argv[2]) [root@localhost checksalt]#
带附件邮件
#!/usr/bin/python # -*- coding: UTF-8 -*- import smtplib import datetime from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header oneday = datetime.timedelta(days=1) today = datetime.date.today() yesterday = datetime.date.today() - oneday yesterday_time = datetime.datetime.strftime(yesterday, ‘%Y-%m-%d‘) sender = ‘xxxx_xxxx@xxxx.com‘ ##发送者 receivers = [‘xxxx@xxxx.com‘,‘xxxx@xxxx.com‘] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱 #创建一个带附件的实例 message = MIMEMultipart() message[‘From‘] = Header("来源", ‘utf-8‘) message[‘To‘] = Header("目的", ‘utf-8‘) subject = ‘xxxx日志‘ message[‘Subject‘] = Header(subject, ‘utf-8‘) #邮件正文内容 message.attach(MIMEText(‘%sxxxx日志信息,请看附件!!‘% yesterday_time, ‘plain‘, ‘utf-8‘)) # 构造附件,传送当前目录下的 test.txt 文件 try: file = ‘file.log.%s‘ % yesterday_time print file att1 = MIMEText(open(file, ‘rb‘).read(), ‘base64‘, ‘utf-8‘) att1["Content-Type"] = ‘application/octet-stream‘ # 这里的filename可以任意写,写什么名字,邮件中显示什么名字 att1["Content-Disposition"] = "attachment; filename=extProfile.log.%s" %yesterday_time message.attach(att1) smtpObj = smtplib.SMTP() smtpObj.connect(‘smtp.exmail.qq.com‘) smtpObj.login(‘xxxx_xxxx@xxxx.com‘, ‘xxxxxxxxxxxx‘) # XXX为用户名,XXXXX为密码 smtpObj.sendmail(sender, receivers, message.as_string()) smtpObj.quit() print "邮件发送成功" except smtplib.SMTPException as e : print str(e) print "Error: 无法发送邮件" except IOError as e: print str(e) print "Error: 无法发送邮件"
本文出自 “奋斗吧” 博客,请务必保留此出处http://lvnian.blog.51cto.com/7155281/1854515
Python 发邮件
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。