首页 > 编程语言 >Python发送QQ邮件

Python发送QQ邮件

时间:2022-11-01 16:46:07浏览次数:66  
标签:QQ __ Python smtp msg import email 邮件

Python发送QQ邮件

1、登陆QQ邮箱,获取授权码

可以参考 官网说明

image-20220516130713724

  • 点击设置

image-20220516130856063

点击账户、点击开启POP3/SMEP服务

image-20220516130944697

点击开启后验证密保,然后根据操作发送短信

image-20220516131044710

image-20220516131152989

然后你就得到了你的授权码

2、发送文本邮件

发送一个只需要显示普通文字的邮件

import datetime
import smtplib
import time
from email.mime.text import MIMEText


def main():
    email_host = "smtp.qq.com"
    email_port = 465
    email_sender = "[email protected]"
    password = 'xxxxxxxxxxxxxxxx'
    email_receiver = ["[email protected]"]
    email_cc = ["[email protected]"]

    body = """测试Python发送邮件【正文】
今天是 {}
现在的时间是 {}
测试正文完毕~~~~
""".format(datetime.datetime.today().strftime("%Y年%m月%d日"),
           time.strftime('%H:%M:%S', time.localtime()))

    msg = MIMEText(body, 'plain')
    msg["Subject"] = "邮件的主题"  # 邮件主题描述
    msg["From"] = email_sender  # 发件人显示,不起实际作用,只是显示一下
    msg["To"] = ",".join(email_receiver)  # 收件人显示,不起实际作用,只是显示一下
    msg["Cc"] = ",".join(email_cc)  # 抄送人显示,不起实际作用,只是显示一下

    with smtplib.SMTP_SSL(email_host, email_port) as smtp:  # 指定邮箱服务器
        smtp.login(email_sender, password)  # 登录邮箱
        smtp.sendmail(email_sender, email_receiver, msg.as_string())  # 分别是发件人、收件人、格式
        smtp.quit()
    print("发送邮件成功!")


if __name__ == '__main__':
    main()

邮件显示

image-20221101154119559

3、发送HTML格式的邮件

import datetime
import smtplib
import time
from email.mime.text import MIMEText


def main():
    email_host = "smtp.qq.com"
    email_port = 465
    email_sender = "[email protected]"
    password = 'xxxxxxxxxxxxxxxx'
    email_receiver = ["[email protected]"]
    email_cc = ["[email protected]"]

    body = """测试Python发送邮件【正文】
<H1>今天是 {}</H1>
<H2>现在的时间是 {}</H2>
<p style="
    color: tomato;
">测试正文完毕~~~~</p>
""".format(datetime.datetime.today().strftime("%Y年%m月%d日"),
           time.strftime('%H:%M:%S', time.localtime()))

    msg = MIMEText(body, 'html')
    msg["Subject"] = "邮件的主题-发送HTML格式的邮件"  # 邮件主题描述
    msg["From"] = email_sender  # 发件人显示,不起实际作用,只是显示一下
    msg["To"] = ",".join(email_receiver)  # 收件人显示,不起实际作用,只是显示一下
    msg["Cc"] = ",".join(email_cc)  # 抄送人显示,不起实际作用,只是显示一下

    with smtplib.SMTP_SSL(email_host, email_port) as smtp:  # 指定邮箱服务器
        smtp.login(email_sender, password)  # 登录邮箱
        smtp.sendmail(email_sender, email_receiver, msg.as_string())  # 分别是发件人、收件人、格式
        smtp.quit()
    print("发送邮件成功!")


if __name__ == '__main__':
    main()

邮件显示

image-20221101154809161

4、发送带附件的邮件

import datetime
import smtplib
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


def main():
    email_host = "smtp.qq.com"
    email_port = 465
    email_sender = "[email protected]"
    password = 'xxxxxxxxxxxxxxxx'
    email_receiver = ["[email protected]"]
    email_cc = ["[email protected]"]

    body_html = """测试Python发送邮件【正文】
    <H1>今天是 {}</H1>
    <H2>现在的时间是 {}</H2>
    <p style="
        color: tomato;
    ">测试正文完毕~~~~</p>
    """.format(datetime.datetime.today().strftime("%Y年%m月%d日"),
               time.strftime('%H:%M:%S', time.localtime()))

    msg = MIMEMultipart()
    msg.attach(MIMEText(body_html, 'html'))  # 添加HTML格式内容

    att = MIMEText(open('files/172.17.140.80-CPU使用率.png', 'rb').read(), 'base64', 'utf-8')
    att["Content-Type"] = 'application/octet-stream'
    att.add_header("Content-Disposition", "attachment", filename=("utf-8", "", "172.17.140.80-CPU使用率.png"))
    msg.attach(att)  # 添加附件

    with open('files/audit_auditrecord.json', 'rb') as f:
        json_content = f.read()
    att2 = MIMEText(json_content, 'base64', 'utf-8')
    att2["Content-Type"] = 'application/octet-stream'
    att2.add_header("Content-Disposition", "attachment", filename=("utf-8", "", "audit_auditrecord.json"))
    msg.attach(att2)  # 添加附件

    msg["Subject"] = "邮件的主题-带附件的邮件"  # 邮件主题描述
    msg["From"] = email_sender  # 发件人显示,不起实际作用,只是显示一下
    msg["To"] = ",".join(email_receiver)  # 收件人显示,不起实际作用,只是显示一下
    msg["Cc"] = ",".join(email_cc)  # 抄送人显示,不起实际作用,只是显示一下

    with smtplib.SMTP_SSL(email_host, email_port) as smtp:  # 指定邮箱服务器
        smtp.login(email_sender, password)  # 登录邮箱
        smtp.sendmail(email_sender, email_receiver, msg.as_string())  # 分别是发件人、收件人、格式
        smtp.quit()
    print("发送邮件成功!")


if __name__ == '__main__':
    main()

邮件显示

image-20221101160725170

5、发送正文直接显示图片的邮件

import datetime
import smtplib
import time
import uuid
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


def main():
    email_host = "smtp.qq.com"
    email_port = 465
    email_sender = "[email protected]"
    password = 'gquzhzcutxnnhjfd'
    email_receiver = ["[email protected]"]
    email_cc = ["[email protected]"]

    u = uuid.uuid4().hex  # 作为图片的唯一ID
    u2 = uuid.uuid4().hex  # 作为图片的唯一ID
    body_html = """测试Python发送邮件【正文】
    <H1>今天是 {}</H1>
    <H2>现在的时间是 {}</H2>
    <p style="
        color: tomato;
    ">测试正文完毕~~~~</p>
    <p><img src="cid:{}"></p>
    <p><img src="cid:{}" width="600px" height="600px"></p>
    """.format(datetime.datetime.today().strftime("%Y年%m月%d日"),
               time.strftime('%H:%M:%S', time.localtime()), u, u2)

    msg = MIMEMultipart()
    msg.attach(MIMEText(body_html, 'html'))  # 添加HTML格式内容

    with open('files/172.17.140.80-CPU使用率.png', 'rb') as f:
        content = f.read()
    img = MIMEImage(content)
    img.add_header('Content-ID', f'{u}')  # 定义图片 ID,在 HTML 文本中引用
    msg.attach(img)

    with open('files/172.17.140.120-CPU使用率.png', 'rb') as f:
        content = f.read()
    img = MIMEImage(content)
    img.add_header('Content-ID', f'{u2}')  # 定义图片 ID,在 HTML 文本中引用
    msg.attach(img)

    msg["Subject"] = "邮件的主题-正文直接显示图片的邮件"  # 邮件主题描述
    msg["From"] = email_sender  # 发件人显示,不起实际作用,只是显示一下
    msg["To"] = ",".join(email_receiver)  # 收件人显示,不起实际作用,只是显示一下
    msg["Cc"] = ",".join(email_cc)  # 抄送人显示,不起实际作用,只是显示一下

    with smtplib.SMTP_SSL(email_host, email_port) as smtp:  # 指定邮箱服务器
        smtp.login(email_sender, password)  # 登录邮箱
        smtp.sendmail(email_sender, email_receiver, msg.as_string())  # 分别是发件人、收件人、格式
        smtp.quit()
    print("发送邮件成功!")


if __name__ == '__main__':
    main()

邮件显示

image-20221101163143399

参考链接

标签:QQ,__,Python,smtp,msg,import,email,邮件
From: https://www.cnblogs.com/rainbow-tan/p/16848236.html

相关文章

  • python 二维码检测-
    参考文章:使用微信扫一扫二维码接口解密QRcode-知乎(zhihu.com) importcv2importnumpyasnpimportosdefopen_img(img_dir):img_list=[]for_,......
  • 关于Python封装函数的几道练习题
    1.封装函数,可以判断一个数字是否为偶数deffunc(n):ifn%2==0:print("%d是偶数"%n)else:print("%d是奇数"%n)func(11)#11是奇数2.封装......
  • python基础复习
    目录今日内容概要管理员功能说明及建议总复习函数模块homework今日内容概要管理员功能说明及建议1、冻结账户2、删除账户3、查看/修改指定用户各项数据(密码、购物车)......
  • vs2013配置python 安装第三方工具包
    这里以matplotlib安装为例。选择pip搜索camelcase进行安装。   ......
  • vs2013配置python_vs2013如何安装python
    vs2013如何安装python?步骤如下:1、安装PTVS:下载PTVS①找到下图位置,下载PythonToolsforVS2013地址:https://github.com/Microsoft/PTVS/releases/v2.2.2 ②安装RT......
  • PG plpython存储过程计算结果直接入库
    >处理函数(返回多条结果数组)dropFUNCTIONcal_charge_sample(recordsdwd_pv_behavior_di[]);CREATEFUNCTIONcal_charge_sample(recordsdwd_pv_behavior_di[])R......
  • Python 变量作用域
    一、Python中变量作用域分为以下四种,简称LEGB:Local局部变量Enclosed嵌套变量Global全局变量Built-in内置变量Local局部变量:暂时的存在,依赖于创建该局部作用......
  • 拓端tecdat|python代写辅导虎扑社区论坛数据爬虫分析报告
    以下是摘自虎扑的官方介绍:虎扑是为年轻男性服务的专业网站,涵盖篮球、足球、F1、NFL等赛事的原创新闻专栏视频报道,拥有大型的生活/影视/电竞/汽车/数码网上交流社区,聊体育谈......
  • vscode下如何把缩进为2个空格的python项目改为4个空格的缩进
    最近在看老项目的代码,是python2.7年代的项目,那个时候很多的python项目都是使用2个空格,不过现在估计大多数人写python项目都是使用4个空格的了,而我看这两个空格的项目代码也......
  • Python Selenium 获取页面所有文本内容
    分享知识 传递快乐用Selenium爬虫获取网页上显示的文本,首先安装lxml模块:pipinstalllxml代码:driver=webdriver.Chrome()driver.maximize_window()driver.get("url"......