首页 > 编程 > Python > 正文

Python实现发送QQ邮件的封装

2020-02-16 01:52:57
字体:
来源:转载
供稿:网友

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

封装code

import smtplibfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.header import Header# type=plain 文本格式 默认# type=html 网页格式# type=image 带本地图片的html# type=file 带附件# 带图片时,msg为html格式# 示例:'''msg ='<p>Python 邮件发送测试...</p><p>图片演示:</p><p><img src="cid:image1"></p>''''class MyQQEmail: __mail_user = '' # 登陆邮箱 __mail_pass = '' # 邮箱授权码 __senderName= '' # 发件人 def __init__(self,user,pas,name) -> None:  self.__mail_user=user  self.__mail_pass=pas  self.__senderName=name def sendQQEmail(self,receiver, title, msg, type='plain', filePaths=[], fileNames=[], imagePaths=None):  if receiver == '':   return False  mail_host = 'smtp.qq.com'  mail_port = 465 # qq smtp端口465  sender = self.__mail_user  type = type.lower()  if type.__eq__('plain') or type.__eq__('html'):   message = MIMEText(msg, type, 'utf-8')  elif type.__eq__('file') or type.__eq__('image'):   message = MIMEMultipart()  else:   return False  try:   message['From'] = Header(self.__senderName, 'utf-8')   message['To'] = Header(str(receiver), 'utf-8')   subject = title   message['Subject'] = Header(subject, 'utf-8')   if type.__eq__('file') or type.__eq__('image'):    # 邮件正文内容    if imagePaths is not None:     message.attach(MIMEText(msg, 'html', 'utf-8'))     # 添加图片     if imagePaths is not None:      for index,imagePath in enumerate(imagePaths,1):       # 指定图片为当前目录       fp = open(imagePath, 'rb')       msgImage = MIMEImage(fp.read())       fp.close()       # 定义图片 ID,在 HTML 文本中引用       msgImage.add_header('Content-ID', '<image'+str(index)+'>')       message.attach(msgImage)    else:     message.attach(MIMEText(msg, 'plain', 'utf-8'))    # 构造附件,传送filePath制定文件    for filePath, fileName in zip(filePaths, fileNames):     att = MIMEText(open(filePath, 'rb').read(), 'base64', 'utf-8')     att["Content-Type"] = 'application/octet-stream'     # 邮件中显示文件名     att["Content-Disposition"] = 'attachment; filename="' + fileName + '"'     message.attach(att)  except Exception as e:   print(e)   return False  try:   smtpObj = smtplib.SMTP_SSL(mail_host, mail_port)   smtpObj.login(self.__mail_user, self.__mail_pass)   smtpObj.sendmail(sender, receiver, message.as_string())   smtpObj.quit()   return True  except Exception as e:   print(e)   return False

使用demo

发送纯文本

qq=MyQQEmail('登陆邮箱','邮箱授权码','发件人')qq.sendQQEmail(['收件人邮箱1','收件人邮箱2'], "标题", '内容')

发送html

from smtp.myqqemail import MyQQEmailfrom urllib import requestresponse = request.urlopen("http://www.vove7.cn:800/getCopyright.php") # 打开网站htmlContent=response.read()   #获取网站内容myqqemail=MyQQEmail('xxx@qq.com','xxxxxx','发件人')if myqqemail.sendQQEmail(['xxx@qq.com'],title="html测试",msg=htmlContent,type='html'):  print('Send successful')else:  print('Send failed')            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表