使用 Python 发送邮件到 Outlook 邮箱
在日常工作和生活中,我们经常需要使用邮件进行沟通和传递信息。Python 语言提供了多种库和工具,可以帮助我们轻松地发送邮件。本文将介绍如何使用 Python 发送邮件到 Outlook 邮箱,并提供相应的代码示例。
准备工作
在进行代码编写之前,我们需要准备好以下工作:
- 安装 Python 环境
- 获取 Outlook 邮箱的 SMTP 服务器地址和授权码
- 安装 Python 的邮件发送库
smtplib
和email
发送邮件代码示例
下面是一个简单的 Python 脚本,用来发送邮件到 Outlook 邮箱:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 发件人邮箱
sender = 'your_email@outlook.com'
# 收件人邮箱
receiver = 'recipient_email@outlook.com'
# Outlook 邮箱的 SMTP 服务器地址
smtp_server = 'smtp-mail.outlook.com'
# 发件人邮箱授权码
password = 'your_password'
# 邮件内容
message = MIMEText('This is a test email sent from Python.', 'plain', 'utf-8')
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(receiver, 'utf-8')
message['Subject'] = Header('Test Email', 'utf-8')
# 连接 SMTP 服务器并发送邮件
server = smtplib.SMTP(smtp_server, 587)
server.starttls()
server.login(sender, password)
server.sendmail(sender, receiver, message.as_string())
server.quit()
print('Email sent successfully!')
在上面的代码中,我们首先导入了必要的库,然后设置了发件人邮箱、收件人邮箱、SMTP 服务器地址和发件人邮箱授权码。接着创建了邮件内容并连接到 SMTP 服务器,最后发送邮件并输出提示信息。
旅行图
journey
title Sending Email to Outlook Mailbox
section Prepare
Python环境安装: 2022-01-01
获取SMTP服务器和授权码: 2022-01-02
section Code
编写Python脚本: 2022-01-03
运行发送邮件: 2022-01-04
section Complete
邮件发送成功: 2022-01-05
序列图
sequenceDiagram
participant Sender
participant Server
participant Receiver
Sender ->> Server: 连接SMTP服务器
Server -->> Sender: 连接成功
Sender ->> Server: 发送邮件内容
Server -->> Sender: 发送成功
Sender ->> Server: 断开连接
Server -->> Sender: 连接关闭
通过上面的代码示例和图示,我们可以轻松地使用 Python 发送邮件到 Outlook 邮箱。希望本文对您有所帮助,祝您使用愉快!