Python使用QQ邮箱smtp服务发送邮件

一丶设置QQ邮箱

网址:mail.qq.com/

使用自己的QQ账号密码登录到QQ邮箱,点击设置,然后选择账户,

Python使用QQ邮箱smtp服务发送邮件_第1张图片

将这些服务开启,然后选择“生成授权码”,

Python使用QQ邮箱smtp服务发送邮件_第2张图片

按照提示,发送完短信后就可以得到授权码了,我们可以用这个授权码作为密码第三方登录QQ邮箱,

Python使用QQ邮箱smtp服务发送邮件_第3张图片

二丶Python程序发送邮件

# -*- coding: utf-8 -*-

import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart

sender = '[email protected]'  # 发送者邮箱
password = 'xxxxxxxxxxxxxxxx'  # 授权码
user = '[email protected]'  # 接收者邮箱

def mail():
    ret = True
    try:
        """
        msg = MIMEText("This is liujian's first SMTP program", 'plain', 'utf-8')
        msg['From'] = formataddr(["我是巴伯你是谁", sender])
        msg['To'] = formataddr(["LJ", user])
        msg['Subject'] = "发送邮件测试"
        """

        msg = MIMEMultipart()
        msg['From'] = formataddr(["我是巴伯你是谁", sender])
        msg['To'] = formataddr(["LJ", user])
        msg['Subject'] = "Python发送邮件测试"
        msg.attach(MIMEText('这是我的第二个Python邮件程序', 'plain', 'utf-8'))
        att1 = MIMEText(open('text.txt', 'rb').read(), 'base64', 'utf-8')   # 添加附件
        att1["Content-Type"] = 'application/octet-stream'
        att1["Content-Disposition"] = 'attachment; filename="text.txt"'
        msg.attach(att1)

        msgPicture = MIMEMultipart()
        msg.attach(msgPicture)  # 添加图片
        mail_msg = """
        

Python 邮件发送测试...

百度搜索

""" msgPicture.attach(MIMEText(mail_msg, 'html', 'utf-8')) # 添加网址 fp = open('test.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '') # 定义图片id,在html中引用 msg.attach(msgImage) server = smtplib.SMTP_SSL("smtp.qq.com", 465) # smtp服务器地址和端口号 server.login(sender, password) server.sendmail(sender, [user, ], msg.as_string()) server.quit() except Exception: ret = False return ret ret = mail() if ret: print ("发送邮件成功") else: print ("发送邮件失败")

上述历程发送了一封带有文档附件,图片和网址链接的邮件,收到的邮件内容如下:

Python使用QQ邮箱smtp服务发送邮件_第4张图片

你可能感兴趣的:(Python使用QQ邮箱smtp服务发送邮件)