098、Python 通过编程实现发送邮件的方法

要通过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所发送的邮件!

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不在同一频道上的呆子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值