Python 邮件发送附件教程

概述

本文将介绍如何使用 Python 发送带有附件的邮件。我们将通过以下步骤来实现这个功能:

  1. 连接到邮件服务器
  2. 创建邮件对象
  3. 添加附件
  4. 发送邮件

详细步骤

1. 连接到邮件服务器

首先,我们需要连接到邮件服务器。在 Python 中,我们可以使用 smtplib 模块来实现这一步骤。以下是连接到邮件服务器的代码:

import smtplib

# 创建 SMTP 对象
smtpObj = smtplib.SMTP('smtp.example.com', 587)

# 开启 TLS 连接(如果需要)
smtpObj.starttls()

# 登录到邮件服务器
smtpObj.login('your_email@example.com', 'your_password')

在上面的代码中,需要将 smtp.example.com 替换为你的邮件服务器的地址,587 替换为端口号(通常为 587),your_email@example.com 替换为你的邮箱地址,your_password 替换为你的邮箱密码。

2. 创建邮件对象

接下来,我们需要创建一个邮件对象,以便填写邮件的内容。我们可以使用 email 模块来实现这一步骤。以下是创建邮件对象的代码:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# 创建邮件对象
msg = MIMEMultipart()

# 设置邮件的收件人、发件人和主题
msg['From'] = 'your_email@example.com'
msg['To'] = 'recipient_email@example.com'
msg['Subject'] = '邮件主题'

# 添加邮件正文
body = '这是邮件的正文部分'
msg.attach(MIMEText(body, 'plain'))

在上面的代码中,需要将 your_email@example.com 替换为你的邮箱地址,recipient_email@example.com 替换为收件人的邮箱地址,邮件主题 替换为邮件的主题,这是邮件的正文部分 替换为邮件的正文内容。

3. 添加附件

现在,我们可以添加附件到邮件中。我们需要使用 email 模块中的 MIMEBase 类来实现这一步骤。以下是添加附件的代码:

from email.mime.base import MIMEBase
from email import encoders

# 打开要发送的附件文件
attachment = open('path_to_attachment_file', 'rb')

# 创建 MIMEBase 对象
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename= "attachment_filename"')

# 将附件添加到邮件对象中
msg.attach(part)

在上面的代码中,需要将 path_to_attachment_file 替换为附件文件的路径,attachment_filename 替换为附件文件的名称。

4. 发送邮件

最后,我们需要发送邮件。我们可以使用 smtplib 模块中的 sendmail 函数来实现这一步骤。以下是发送邮件的代码:

# 发送邮件
smtpObj.sendmail('your_email@example.com', 'recipient_email@example.com', msg.as_string())

# 关闭连接
smtpObj.quit()

在上面的代码中,需要将 your_email@example.com 替换为你的邮箱地址,recipient_email@example.com 替换为收件人的邮箱地址。

完整代码示例

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

# 创建 SMTP 对象
smtpObj = smtplib.SMTP('smtp.example.com', 587)
smtpObj.starttls()

# 登录到邮件服务器
smtpObj.login('your_email@example.com', 'your_password')

# 创建邮件对象
msg = MIMEMultipart()
msg['From'] = 'your_email@example.com'
msg['To'] = 'recipient_email@example.com'
msg['Subject'] = '邮件主题'

# 添加邮件正文
body = '这是邮件的正文部分'
msg.attach(MIMEText(body, 'plain'))

# 添加附件
attachment = open('path_to_attachment_file', 'rb')
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64