打开qq邮箱的设置:
- 获取授权码:
- 开启如图配置:
- 点击 生成授权码 ,复制
send_email.py代码:
import smtplib
import email
from email.mime.text import MIMEText # 负责构造文本
from email.mime.image import MIMEImage # 负责构造图片
from email.mime.multipart import MIMEMultipart # 负责将多个对象集合起来
from email.header import Header
def send_email(f_name,subject_content, body_content):
"""
f_name:上传的附件的路径
subject_content: 邮件主题
body_content: 邮件文本内容
:return:
"""
# 构建MIMEMultipart对象代表邮件本身,可以往里面添加文本、图片、附件等
mm = MIMEMultipart('related')
# 邮件主题
subject_content = subject_content
# 设置发送者,注意严格遵守格式,里面邮箱为发件人邮箱
mm["From"] = "sender_name<{}>".format(mail_sender)
# 设置接受者,注意严格遵守格式,里面邮箱为接受者邮箱
mm["To"] = "receiver_1_name<{}>".format(mail_receivers)
# 设置邮件主题
mm["Subject"] = Header(subject_content, 'utf-8')
# 邮件正文内容
body_content = body_content
# 构造文本,参数1:正文内容,参数2:文本格式,参数3:编码方式
message_text = MIMEText(body_content, "plain", "utf-8")
# 向MIMEMultipart对象中添加文本对象
mm.attach(message_text)
# 构造附件
atta = MIMEText(open('{}'.format(f_name), 'rb').read(), 'base64', 'utf-8')
# 设置附件信息
atta["Content-Disposition"] = 'attachment; filename={}'.format(f_name)
# 添加附件到邮件信息当中去
mm.attach(atta)
# 创建SMTP对象
stp = smtplib.SMTP_SSL("smtp.qq.com", 465)
# set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息
stp.set_debuglevel(1)
# 登录邮箱,传递参数1:邮箱地址,参数2:邮箱授权码
stp.login(mail_sender, 'psldyaxwwltqbgbd')
# 发送邮件,传递参数1:发件人邮箱地址,参数2:收件人邮箱地址,参数3:把邮件内容格式改为str
stp.sendmail(mail_sender, mail_receivers, mm.as_string())
print("邮件发送成功")
# 关闭SMTP对象
stp.quit()
return 'ok'
# SMTP服务器,这里使用qq邮箱
mail_host = "smtp.qq.com"
# 发件人邮箱
mail_sender = "39017764@qq.com"
# 邮箱授权码,注意这里不是邮箱密码,如何获取邮箱授权码
mail_license = "复制的授权码"
# 收件人邮箱,可以为多个收件人
mail_receivers = "xiao3901@foxmail.com"
# mail_receivers = ["xiao3901@foxmail.com",'xx@xx.com'] # 多个收件人
# 构建MIMEMultipart对象代表邮件本身,可以往里面添加文本、图片、附件等
mm = MIMEMultipart('related')
f_name = 'qwq.xlsx' # 本地文件名
subject_content = """Python邮件测试""" # 邮件主题
body_content = """你好,这是一个测试邮件!""" # 邮件文本内容
send_email(f_name, subject_content, body_content)
收件人视图: