Python 进阶—使用SMTP 发送邮件

版权声明:如需转载请标注 https://blog.csdn.net/weixin_40973138/article/details/84134294

本文针对QQ邮箱的邮件发送,163邮箱与之类似

1. 首先应在邮箱中开启SMTP 服务并获得授权码:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在开启了SMTP 服务之后我们会获得授权码(授权码可有多个,均可正常使用):
在这里插入图片描述
在这里插入图片描述

2. 使用Python3 发送简单邮件

Python对SMTP 支持有smtplibemail 两个模块,email 负责构造邮件,smtplib 负责发送邮件

import smtplib
from email.header import Header          # 用来设置邮件头和邮件主题
from email.mime.text import MIMEText     # 发送正文只包含简单文本的邮件,引入MIMEText即可

def send_email(sender_email, reciver_email, authorization_code, smtp_server, email_title, email_body):

	message = MIMEText(email_body, 'plain', 'utf-8')   # 邮件正文,'plain'表示纯文本,'utf-8'保证多语言兼容性
	message['From'] = sender_email                     # 邮件上显示的发件人
	message['To'] = reciver_email                      # 邮件上显示的收件人
	message['Subject'] = Header(email_title, 'utf-8')  # 邮件主题
	 
	try:
	    smtp = smtplib.SMTP()                           # 创建一个连接
	    smtp.connect(smtp_server)                       # 连接发送邮件的服务器
	    smtp.login(sender_email, authorization_code)    # 登录服务器
	    smtp.sendmail(sender_email, reciver_email, message.as_string())  # 填入邮件的相关信息并发送
	    print("邮件发送成功!!!")
	    smtp.quit()
	except smtplib.SMTPException:
	    print("邮件发送失败!!!")

title = 'Test'
body = 'This is a test'
send_email('[email protected]', '[email protected]', 'ickdbbikbbXXXXXX', 'smtp.qq.com', title, body)

代码参数说明:

参数 说明
sender_email 发件人邮箱
reciver_email 收件人邮箱
authorization_code 授权码
smtp_server SMTP 服务器地址
email_title 邮件主题
email_body 邮件正文

邮件发送结果:在这里插入图片描述

若将代码第13 行修改为smtp = smtplib.SMTP_SSL() 可实现SSL 加密,虽然我并不觉得有什么不同…

顺便补充一下:

网易STMP 服务器和端口 QQ STMP 服务器和端口
smtp.163.com smtp.qq.com
465 465

3. 程序小升级

import smtplib
from email.header import Header          # 用来设置邮件头和邮件主题
from email.mime.text import MIMEText     # 发送正文只包含简单文本的邮件,引入MIMEText即可

def send_email(sender_email, reciver_list_email, authorization_code, smtp_server, email_title, email_body):

	message = MIMEText(email_body, 'plain', 'utf-8')   # 邮件正文,'plain'表示纯文本,'utf-8'保证多语言兼容性
	message['From'] = sender_email                     # 邮件上显示的发件人
	message['To'] = reciver_email                      # 邮件上显示的收件人
	message['Subject'] = Header(email_title, 'utf-8')  # 邮件主题
	 
	try:
	    smtp = smtplib.SMTP()                           # 创建一个连接
	    smtp.connect(smtp_server)                       # 连接发送邮件的服务器
	    smtp.login(sender_email, authorization_code)    # 登录服务器
	    smtp.sendmail(sender_email, reciver_list_email, message.as_string())  # 填入邮件的相关信息并发送
	    print("邮件发送成功!!!")
	    smtp.quit()
	except smtplib.SMTPException:
	    print("邮件发送失败!!!")

title = 'Test'
body = 'This is a test'
send_email('[email protected]', ['[email protected]', '[email protected]'], 'ickdbbikbbXXXXXX', 'smtp.qq.com', title, body)

收件人邮箱由单个变为列表,将收件人由单个变为多个。

猜你喜欢

转载自blog.csdn.net/weixin_40973138/article/details/84134294