侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

Python smtplib实现发送邮件功能

Python  /  管理员 发布于 7年前   158

本文实例为大家分享了Python smtplib发送邮件功能的具体代码,供大家参考,具体内容如下

解决之前版本的问题,下面为最新版

#!/usr/bin/env python # coding:gbk  """ FuncName: sendemail.py Desc: sendemail with text,image,audio,application... Date: 2016-06-20 10:30 Home: http://blog.csdn.net/z_johnny Author: johnny """  from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication from email.utils import COMMASPACE from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.audio import MIMEAudio import ConfigParser import smtplib import os  class MyEmail:  def __init__(self, email_config_path, email_attachment_path):   """   init config   """   config = ConfigParser.ConfigParser()   config.read(email_config_path)   self.attachment_path = email_attachment_path    self.smtp = smtplib.SMTP()   self.login_username = config.get('SMTP', 'login_username')   self.login_password = config.get('SMTP', 'login_password')   self.sender = config.get('SMTP', 'login_username') # same as login_username   self.receiver = config.get('SMTP', 'receiver')   self.host = config.get('SMTP', 'host')   #self.port = config.get('SMTP', 'port')  发现加入端口后有时候发邮件出现延迟,故暂时取消   def connect(self):   """   connect server   """   #self.smtp.connect(self.host, self.port)   self.smtp.connect(self.host)   def login(self):   """   login email   """   try:    self.smtp.login(self.login_username, self.login_password)   except:    raise AttributeError('Can not login smtp!!!')   def send(self, email_title, email_content):   """   send email   """   msg = MIMEMultipart()     # create MIMEMultipart   msg['From'] = self.sender    # sender   receiver = self.receiver.split(",")  # split receiver to send more user   msg['To'] = COMMASPACE.join(receiver)   msg['Subject'] = email_title   # email Subject   content = MIMEText(email_content, _charset='gbk') # add email content ,coding is gbk, becasue chinese exist   msg.attach(content)    for attachment_name in os.listdir(self.attachment_path):    attachment_file = os.path.join(self.attachment_path,attachment_name)     with open(attachment_file, 'rb') as attachment:     if 'application' == 'text':      attachment = MIMEText(attachment.read(), _subtype='octet-stream', _charset='GB2312')     elif 'application' == 'image':      attachment = MIMEImage(attachment.read(), _subtype='octet-stream')     elif 'application' == 'audio':      attachment = MIMEAudio(attachment.read(), _subtype='octet-stream')     else:      attachment = MIMEApplication(attachment.read(), _subtype='octet-stream')     attachment.add_header('Content-Disposition', 'attachment', filename = ('gbk', '', attachment_name))    # make sure "attachment_name is chinese" right    msg.attach(attachment)    self.smtp.sendmail(self.sender, receiver, msg.as_string()) # format msg.as_string()   def quit(self):   self.smtp.quit()  def send():  import time  ISOTIMEFORMAT='_%Y-%m-%d_%A'  current_time =str(time.strftime(ISOTIMEFORMAT))   email_config_path = './config/emailConfig.ini' # config path  email_attachment_path = './result'    # attachment path  email_tiltle = 'johnny test'+'%s'%current_time # as johnny test_2016-06-20_Monday ,it can choose only file when add time  email_content = 'python发送邮件测试,包含附件'   myemail = MyEmail(email_config_path,email_attachment_path)  myemail.connect()  myemail.login()  myemail.send(email_tiltle, email_content)  myemail.quit()  if __name__ == "__main__":  # from sendemail import SendEmail  send() 

配置文件emailConfig.ini

路径要与程序对应

;login_username : 登陆发件人用户名 ;login_password : 登陆发件人密码 ;host:port : 发件人邮箱对应的host和端口,如:smtp.163.com:25 和 smtp.qq.com:465 ;receiver : 收件人,支持多方发送,格式(注意英文逗号): [email protected],[email protected] [SMTP] login_username = [email protected] login_password = johnny host = smtp.163.com port = 25 receiver = [email protected],[email protected],[email protected] 

之前版本出现的问题:

#!/usr/bin/env python #coding: utf-8  ''''' FuncName: smtplib_email.py Desc: 使用smtplib发送邮件 Date: 2016-04-11 14:00 Author: johnny '''  import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email.utils import COMMASPACE,formatdate from email import encoders  def send_email_text(sender,receiver,host,subject,text,filename):    assert type(receiver) == list   msg = MIMEMultipart()  msg['From'] = sender  msg['To'] = COMMASPACE.join(receiver)  msg['Subject'] = subject  msg['Date'] = formatdate(localtime=True)  msg.attach(MIMEText(text))     #邮件正文内容   for file in filename:      #邮件附件   att = MIMEBase('application', 'octet-stream')   att.set_payload(open(file, 'rb').read())   encoders.encode_base64(att)   if file.endswith('.html'):    # 若不加限定,jpg、html等格式附件是bin格式的    att.add_header('Content-Disposition', 'attachment; filename="今日测试结果.html"')   # 强制命名,名称未成功格式化,如果可以解决请联系我   elif file.endswith('.jpg') or file.endswith('.png') :    att.add_header('Content-Disposition', 'attachment; filename="pic.jpg"')   else:    att.add_header('Content-Disposition', 'attachment; filename="%s"' % file)   msg.attach(att)   smtp = smtplib.SMTP(host)    smtp.ehlo()  smtp.starttls()  smtp.ehlo()  smtp.login(username,password)  smtp.sendmail(sender,receiver, msg.as_string())  smtp.close()  if __name__=="__main__":  sender = '[email protected]'  receiver = ['[email protected]']  subject = "测试"  text = "johnny'lab test"  filename = [u'测试报告.html','123.txt',u'获取的信息.jpg']  host = 'smtp.163.com'  username = '[email protected]'  password = 'qqq'  send_email_text(sender,receiver,host,subject,text,filename) 

已测试通过,使用Header并没有变成“头”,故未使用

若能解决附件格式为(html、jpg、png)在邮箱附件中格式不为“bin”的请联系我,希望此对大家有所帮助,谢谢(已解决,见上面最新版)

点击查看:Python 邮件smtplib发送示例 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Python3基于sax解析xml操作示例
    下一条:
    linux下python使用sendmail发送邮件
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客