废话不多说直接上代码!
#!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : 2021/7/7 1:08
# @Author : Yujie_Xue
# @Email : xyj19970628@163.com
# @File : 14.7 发送有附件的邮件.py
# @Software: PyCharm 2019.1
from smtplib import SMTP
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart # 我学习过邮件里面的格式
import urllib
def main():
# 1 创建一个带附件的邮件消息对象
message = MIMEMultipart()
# 2 创建文本内容,并将文本内容添加到邮件消息对象中
text_content = MIMEText('附件中本月数据请查收!', 'plain', 'utf-8')
message['Subject'] = Header('本月数据', 'utf-8')
# 将文本内容添加到邮件消息对象中
message.attach(text_content)
# 3 读取文本文件并将该文件作为附件添加到邮件消息对象中
with open('Users/hello.txt', 'rb') as f:
txt = MIMEText(f.read(), 'base64', 'utf-8')
txt['Content-Type'] = 'text/plain'
txt['Content-Disposition'] = 'attachment; filename=hello.txt'
message.attach(txt)
# 4 读取表格文件并将该文件作为附件添加到邮件消息对象中
with open('Users/报名表.xls', 'rb') as f:
xls = MIMEText(f.read(), 'base64', 'utf-8')
xls['Content-Type'] = 'application/vnd.ms-excel'
xls['Content-Disposition'] = 'attachment; filename=month-data.xls'
message.attach(xls)
# 4.1 读取图片并将图片作为附件添加到邮件消息对象中
with open('Users/guido.jpg', 'rb') as f:
img = MIMEImage(f.read())
img.add_header('Content-ID', '<image1>') # 指定文件的Content-ID,<img>,在HTML中图片src将用到
message.attach(img) # 附件上有一张图片!
# 5 创建SMTP对象
smpter = SMTP('smtp.126.com') # 用什么邮箱发就去找这个邮箱服务器的SMTP
# 6 开启安全连接
# smpter.starttls()
sender = 'youremailaddress@126.com'
receivers = ['otheremailaddress@126.com']
message['From'] = sender
message['To'] = receivers[0]
# 7 登录到SMTP服务器
# 请注意此处不是使用密码而是邮件客户端授权码进行登录
# 对此有疑问的读者可以联系自己使用的邮件服务器客服
smpter.login(sender, 'RQIKLKNIJMMXAAAA')
# 8 发送邮件
smpter.sendmail(sender, receivers, message.as_string())
# 9 断开邮件服务器的连接
smpter.quit()
print('带有附件的邮件发送完成!')
# 下面是不需要发送附件的版本
# # 1 邮件戳准备阶段
# # 请自行修改下面的邮件发送者和接收者
# sender = 'youremailaddress@126.com'
# receivers = 'otheremailaddress@163.com' # 给多个人发邮件这里改成列表,下面两部再写个for循环
#
# # 2 邮件内容
# message = MIMEText('我不会忘记一个很重要的人的!', 'plain', 'utf-8')
# message['From'] = sender
# message['To'] = receivers
# message['Subject'] = Header('记一次美丽的旅行', 'utf-8')
# smtper = SMTP('smtp.126.com')
#
# # 3 登录和发送
# # 请自行修改下面的登录口令
# smtper.login(sender, 'RQIKLKNIJMMXAAAA')
# smtper.sendmail(sender, receivers, message.as_string())
# print('邮件发送完成!')
if __name__ == '__main__':
main()