Python有两个内置库:smtplib和email,能够实现邮件功能,smtplib库负责发送邮件,email库负责构造邮件格式和内容。

邮件发送需要遵守SMTP协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。

1、先导入相关的库和方法

1
2
3
4
5
6
7
8
9
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

2、设置邮箱域名、发件人邮箱、邮箱授权码、收件人邮箱

1
2
3
4
5
6
7
8
# SMTP服务器,这里使用163邮箱
mail_host = "smtp.163.com"
# 发件人邮箱
mail_sender = "******@163.com"
# 邮箱授权码,注意这里不是邮箱密码,如何获取邮箱授权码,请看本文最后教程
mail_license = "********"
# 收件人邮箱,可以为多个收件人
mail_receivers = ["******@qq.com","******@outlook.com"]

3、构建MIMEMultipart对象代表邮件本身,可以往里面添加文本、图片、附件等

1
mm = MIMEMultipart('related')

4、设置邮件头部内容

1
2
3
4
5
6
7
8
# 邮件主题
subject_content = """Python邮件测试"""
# 设置发送者,注意严格遵守格式,里面邮箱为发件人邮箱
mm["From"] = "sender_name<******@163.com>"
# 设置接受者,注意严格遵守格式,里面邮箱为接受者邮箱
mm["To"] = "receiver_1_name<******@qq.com>,receiver_2_name<******@outlook.com>"
# 设置邮件主题
mm["Subject"] = Header(subject_content,'utf-8')

5、添加正文文本

1
2
3
4
5
6
# 邮件正文内容
body_content = """你好,这是一个测试邮件!"""
# 构造文本,参数1:正文内容,参数2:文本格式,参数3:编码方式
message_text = MIMEText(body_content,"plain","utf-8")
# 向MIMEMultipart对象中添加文本对象
mm.attach(message_text)

6、添加图片

1
2
3
4
5
6
7
8
# 二进制读取图片
image_data = open('a.jpg','rb')
# 设置读取获取的二进制数据
message_image = MIMEImage(image_data.read())
# 关闭刚才打开的文件
image_data.close()
# 添加图片文件到邮件信息当中去
mm.attach(message_image)
    # 设置图片附件可直接浏览
    message_image.add_header('Content-ID', '<images1>')
    # 对文件重新命名(如果不加下面这行会在收件方显示乱码的bin文件)
    message_image["Content-Disposition"] = 'attachment; filename="{}'.format(img_name)

7、添加附件(excel表格)

1
2
3
4
5
6
# 构造附件
atta = MIMEText(open('sample.xlsx', 'rb').read(), 'base64', 'utf-8')
# 设置附件信息
atta["Content-Disposition"] = 'attachment; filename="sample.xlsx"'
# 添加附件到邮件信息当中去
mm.attach(atta)

8、发送邮件

1
2
3
4
5
6
7
8
9
10
11
12
13
# 创建SMTP对象
stp = smtplib.SMTP()
# 设置发件人邮箱的域名和端口,端口地址为25
stp.connect(mail_host, 25)
# set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息
stp.set_debuglevel(1)
# 登录邮箱,传递参数1:邮箱地址,参数2:邮箱授权码
stp.login(mail_sender,mail_license)
# 发送邮件,传递参数1:发件人邮箱地址,参数2:收件人邮箱地址,参数3:把邮件内容格式改为str
stp.sendmail(mail_sender, mail_receivers, mm.as_string())
print("邮件发送成功")
# 关闭SMTP对象
stp.quit()

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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
class Send_Email:
def __init__(self):
self.mail_host = 'smtp.163.com' # SMTP服务器,这里使用163邮箱
self.mail_license = 'GCKSUSDNBONOXHGY' # 授权码
self.mail_sender = 'b17876283049@163.com' # 发件人邮箱
self.mail_receivers = ['915228208@qq.com'] # 设置收件人邮箱地址
self.mm = MIMEMultipart('related')

def read_image_add(self,img_path,img_name):
# 二进制读取图片
image_data = open(img_path,'rb')
# 设置读取获取的二进制数据
message_image = MIMEImage(image_data.read())
# 设置图片附件可直接浏览
message_image.add_header('Content-ID', '<images1>')
# 对文件重新命名(如果不加下面这行会在收件方显示乱码的bin文件)
message_image["Content-Disposition"] = 'attachment; filename="{}'.format(img_name)
# 关闭刚才打开的文件
image_data.close()
# 添加图片文件到邮件信息当中去
self.mm.attach(message_image)

def read_file_add(self,file_path,file_name):
# 构造附件
atta = MIMEText(open(file_path,'rb').read,'base64','utf-8')
# 设置附件信息 对文件重新命名
atta["Content-Disposition"] = 'attachment;filename="{}'.format(file_name)
# 添加附件到邮件信息中去
self.mm.attach(atta)

def send_email(self):
# 创建SMTP对象
stp = smtplib.SMTP()
# 设置发送人邮箱的域名的端口,端口地址为25
stp.connect(self.mail_host)
# set_debuglevel(1) 可以打印和SMTP服务器交互所有信息
stp.set_debuglevel(1)
# 登录邮箱,传递参数1:邮箱地址,参数2:邮箱授权码
stp.login(self.mail_sender,self.mail_license)
# 发送邮件,传递参数1:发件人邮箱地址,参数2:收件人邮箱地址,参数3:把邮件内容格式改为str
stp.sendmail(self.mail_sender,self.mail_receivers,self.mm.as_string())
print("邮件发送成功")
# 关闭SMTP对象
stp.quit()
def run(self):
# 设置邮件头部内容
# 邮件主题
subject_content = '''Python邮件测试'''
# 设置返送着,注意遵守格式。里面邮箱为发件人邮箱
self.mm['From'] = "sender_name<{}>".format(self.mail_sender) # sender_name 可以是接收者收显示的名字 (可以自定义)
# 设置接收者,注意严格遵守格式,里面为接收者邮箱
self.mm["TO"] = "receiver_1_name<{}>".format(self.mail_receivers) # "receiver_1_name<******@qq.com>,receiver_2_name<******@outlook.com>" receiver_1_name接收者在收件人看到的 (可以自定义)
# 设置邮箱主题
self.mm["Subject"] = Header(subject_content,'utf-8')


# 添加正文文本
# 邮件正文
body_content = """你好,这是一个测试邮件!"""
# 构造文本,参数1:正文内容,参数2:文本格式,参数3:编码方式
message_text = MIMEText(body_content,'plain','utf-8')
# 向MINEMultipart对象添加文本对象
self.mm.attach(message_text)

def main():
em = Send_Email()
em.run()
em.send_email()


if __name__ == '__main__':
main()