Python 发送QQ邮件封装

封装code

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

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

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’保持一致

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为显示名


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')
发送图片内容带附件
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邮箱登陆授权码

设置->账户->
这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 在Python封装数据库可以使用第三方库pymysql来进行操作。首先需要安装pymysql库(pip install pymysql),然后可以使用该库来连接MySQL数据库并进行增删改查等操作。具体步骤如下: 1. 连接数据库:使用connect函数连接数据库,生成connection对象。\[1\] 2. 创建游标对象:通过connection对象创建游标对象,用于执行SQL语句。\[2\] 3. 对数据库进行增删改查:使用游标对象执行SQL语句,可以进行插入、删除、更新和查询等操作。\[2\] 4. 关闭游标:在操作完成后,需要关闭游标对象。\[2\] 5. 关闭连接:最后需要关闭数据库连接,释放资源。\[2\] 此外,还可以使用其他的第三方库来封装数据库操作,如SQLAlchemy等。这些库提供了更高级的封装,可以简化数据库操作的流程,并提供更多的功能和灵活性。 #### 引用[.reference_title] - *1* [Python 操作MySql数据库(封装、优雅)](https://blog.csdn.net/qq_59142194/article/details/126681062)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [python操作数据库及并封装数据库函数](https://blog.csdn.net/BJ1599449/article/details/117026500)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [封装篇---Python自动化测试之封装数据库Mysql](https://blog.csdn.net/wuyomhchang/article/details/129043078)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值