服务器之家

服务器之家 > 正文

Python实现发送QQ邮件的封装

时间:2020-11-26 00:35     来源/作者:Vove_7

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

封装code

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from 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

发送纯文本

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

发送html

?
1
2
3
4
5
6
7
8
9
10
11
from smtp.myqqemail import MyQQEmail
from urllib import request
 
response = 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')

发送带图片内容

注意图片和<img src="cid:image1"><img src="cid:image2">中'image_index'保持一致

?
1
2
3
4
5
6
7
8
9
10
11
from smtp.myqqemail import MyQQEmail
msg = '<p>Python 邮件发送测试...</p><p>图片演示:</p><p><img src="cid:image1"><img src="cid:image2"></p>'
myQQEmail=MyQQEmail('xxx@qq.com','xxxxxx','发件人')
if myQQEmail.sendQQEmail(
    ['xxx@qq.com'], '图片and附件', msg,
    type='image', filePaths=['../two/t.py', 'B.txt'],
    fileNames=['test.txt', 'B.txt'],
    imagePaths=['image.jpg','image.jpg']):
  print('Send successful')
else:
  print('Send failed')

发送附件

fileName为显示名

?
1
2
3
4
5
6
7
8
9
10
11
from smtp.myqqemail import MyQQEmail
 
qqemail=MyQQEmail('xxx@qq.com','xxxxx','发件人')
if qqemail.sendQQEmail(
    ['xxx@qq.com'],
    '附件',msg='附件测试',
    type='file',filePaths=['../two/t.py','B.txt'],
    fileNames=['test.txt','B.txt']):
  print('Send successful')
else:
  print('Send failed')

发送图片内容带附件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
from smtp.myqqemail import MyQQEmail
 
msg = '<p>Python 邮件发送测试...</p><p>图片演示:</p><p><img src="cid:image1"><img src="cid:image2"></p>'
qqemail=MyQQEmail('xxx@qq.com','xxx','发件人')
if qqemail.sendQQEmail(
    ['xxx@qq.com'],
    '附件&图片',msg,
    type='file',filePaths=['../two/t.py','B.txt'],
    fileNames=['test.txt','B.txt'],
    imagePaths=['image.jpg','image.jpg']):
  print('Send successful')
else:
  print('Send failed')

最后,修改代码可简化参数type

获取QQ邮箱登陆授权码

设置->账户->

Python实现发送QQ邮件的封装

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

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址
电视剧《琉璃》全集在线观看 琉璃美人煞1-59集免费观看地址 2020-08-12
最新idea2020注册码永久激活(激活到2100年)
最新idea2020注册码永久激活(激活到2100年) 2020-07-29
返回顶部