要通过Python编程实现发送邮件,首先得先登录自己的发送邮箱对发送进行相关设置。
一、进行发送邮箱相关设置
1、如下图,点击设置
->POP3/SMTP/IMAP
2、然后开启POP3/SMTP服务,并获取授权码和SMTP服务器的地址,如下图:
点击开启POP3/SMTP服务后,会跳出下图弹窗:
点击继续开启,进入下图页面:
通过扫码发送短信后,就会返回一个授权码了,如下图:
通过以上设置和获取信息,我们就可以进行下面编程了。
二、编程实现发送邮件
Python标准库自带了两个模块smtplib``和``email
用于构建邮件和发送,下面编写如下代码:
"""
example098 - Python 通过编程实现发送邮件的方法
Author: 不在同一频道上的呆子
Date: 2024/7/27
"""
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# 发件人邮箱和密码(注意:这里的密码指的是邮箱的SMTP授权码,而非登录密码)
sender_email = 'your_email@example.com' # 发送人邮箱: 如:your_email@example.com
sender_password = 'your_email_password_or_app_password' # 发送人邮箱授权码:如:your_email_password_or_app_password
# SMTP服务器地址和端口
smtp_server = 'smtp.163.com'
smtp_port = 465
# 收件人邮件
receiver_email = 'receiver_email@example.com' # 收件人邮箱,如:receiver_email@example.com
# 创建邮件对象
message = MIMEMultipart()
message['From'] = "your_email@example.com" # 这里的信头要与信封邮件(即发件人邮箱)地址一致
message['To'] = Header("收件人昵称:你", 'utf-8')
message['Subject'] = Header('邮件主题:测试', 'utf-8')
# 邮件正文内容
message.attach(MIMEText('这是邮件的正文内容,可以是纯文本或HTML。', 'plain', 'utf-8'))
# 邮件附件文件
with open('Resources/test.xlsx', 'rb') as file:
attachment = MIMEText(file.read(), 'base64', 'utf-8')
attachment['content-type'] = 'application/octet-stream'
attachment['content-disposition'] = 'attachment; filename="aaa.xlsx"'
message.attach(attachment)
# 连接到SMTP服务器并发送邮件
try:
server = smtplib.SMTP_SSL(smtp_server, smtp_port) # 使用SMTP_SSL
# 通过用户名和授权码登录
server.login(sender_email, sender_password)
# 发送邮件(发件人、收件人、邮件内容(字符串))
server.sendmail(sender_email, [receiver_email], message.as_string())
server.quit()
print("邮件发送成功")
except smtplib.SMTPException as e:
print("邮件发送失败:", e)
在上面的示例代码中,sender_email参数,即我们的发件人邮箱,sender_password参数,即为我们在上面设置邮箱所获得的授权码,smtp_server参数,即为我们在上面设置邮箱所获得的SMTP服务器的地址。
运行以上代码,返回结果如下:
表示邮件发送成功。
登录接收邮箱,发现能正常接收到Python所发送的邮件!