【Python快速上手(二十七)】- Python3 SMTP发送邮件

Python快速上手(二十七)- Python3 SMTP发送邮件

Python3 SMTP发送邮件

SMTP(Simple Mail Transfer Protocol)是发送电子邮件的标准协议。Python 提供了 smtplib 模块来实现 SMTP 客户端,用于发送电子邮件。本文将详细讲解如何使用 Python3 的 smtplib 模块发送电子邮件,包括基本使用方法、构建复杂邮件、附件处理、安全连接、异常处理和实际应用案例。

1. SMTP 基本概念

在深入讲解之前,了解一些基本概念是必要的:

  • SMTP 服务器:处理发送邮件请求的服务器。常见的 SMTP 服务器有 Gmail、Yahoo、Outlook 等。
  • SMTP 客户端:用于与 SMTP 服务器通信的客户端程序。在本文中,Python 程序将充当 SMTP 客户端。
  • 端口:SMTP 通常使用端口 25,但为了安全起见,TLS/SSL 加密的 SMTP 通常使用端口 587 或 465。

2. 使用 smtplib 发送简单邮件

首先,从发送一封简单的邮件开始。

2.1 设置 SMTP 服务器

要发送邮件,首先需要连接到 SMTP 服务器。

import smtplib

smtp_server = "smtp.example.com"  # 替换为您的 SMTP 服务器地址
port = 587  # 使用适当的端口号
sender_email = "your_email@example.com"  # 发送方邮箱地址
password = "your_password"  # 发送方邮箱密码

# 创建 SMTP 客户端会话对象
server = smtplib.SMTP(smtp_server, port)
2.2 登录到 SMTP 服务器

连接到 SMTP 服务器后,需要进行身份验证。

server.starttls()  # 启用安全加密
server.login(sender_email, password)  # 登录 SMTP 服务器
2.3 发送邮件

登录成功后,可以使用 sendmail 方法发送邮件。

receiver_email = "receiver_email@example.com"  # 接收方邮箱地址
message = """\
Subject: Hi there

This message is sent from Python."""

server.sendmail(sender_email, receiver_email, message)
print("Email sent successfully.")
2.4 关闭连接

邮件发送完成后,需要关闭与 SMTP 服务器的连接。

server.quit()

完整示例代码如下:

import smtplib

smtp_server = "smtp.example.com"
port = 587
sender_email = "your_email@example.com"
password = "your_password"

server = smtplib.SMTP(smtp_server, port)
server.starttls()
server.login(sender_email, password)

receiver_email = "receiver_email@example.com"
message = """\
Subject: Hi there

This message is sent from Python."""

server.sendmail(sender_email, receiver_email, message)
print("Email sent successfully.")
server.quit()

3. 构建复杂邮件

使用 email 模块可以构建带有 HTML 内容、附件等复杂邮件。

3.1 构建带有 HTML 内容的邮件

首先,使用 email.mime.multipart 和 email.mime.text 构建 HTML 邮件。

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

message = MIMEMultipart("alternative")
message["Subject"] = "HTML Email"
message["From"] = sender_email
message["To"] = receiver_email

# 创建纯文本和 HTML 内容
text = """\
Hi,
This is a plain text version of the email."""
html = """\
<html>
  <body>
    <p>Hi,<br>
       This is an <b>HTML</b> version of the email.</p>
  </body>
</html>
"""

# 将内容附加到 MIMEMultipart 对象
part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
message.attach(part1)
message.attach(part2)
3.2 发送带有 HTML 内容的邮件

使用 send_message 方法发送邮件。

server.send_message(message)

完整示例代码如下:

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

smtp_server = "smtp.example.com"
port = 587
sender_email = "your_email@example.com"
password = "your_password"
receiver_email = "receiver_email@example.com"

server = smtplib.SMTP(smtp_server, port)
server.starttls()
server.login(sender_email, password)

message = MIMEMultipart("alternative")
message["Subject"] = "HTML Email"
message["From"] = sender_email
message["To"] = receiver_email

text = """\
Hi,
This is a plain text version of the email."""
html = """\
<html>
  <body>
    <p>Hi,<br>
       This is an <b>HTML</b> version of the email.</p>
  </body>
</html>
"""

part1 = MIMEText(text, "plain")
part2 = MIMEText(html, "html")
message.attach(part1)
message.attach(part2)

server.send_message(message)
print("HTML email sent successfully.")
server.quit()

4. 添加附件

添加附件需要使用 email.mime.base 和 email 模块中的编码功能。

4.1 构建带有附件的邮件
from email.mime.base import MIMEBase
from email import encoders

# 创建一个 MIMEBase 对象
part = MIMEBase("application", "octet-stream")

# 读取附件内容并将其附加到 MIMEBase 对象
filename = "document.pdf"
with open(filename, "rb") as attachment:
    part.set_payload(attachment.read())

# 对附件进行编码并添加到邮件
encoders.encode_base64(part)
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)
message.attach(part)
4.2 发送带有附件的邮件
server.send_message(message)

完整示例代码如下:

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_server = "smtp.example.com"
port = 587
sender_email = "your_email@example.com"
password = "your_password"
receiver_email = "receiver_email@example.com"

server = smtplib.SMTP(smtp_server, port)
server.starttls()
server.login(sender_email, password)

message = MIMEMultipart()
message["Subject"] = "Email with Attachment"
message["From"] = sender_email
message["To"] = receiver_email

text = """\
Hi,
This email contains an attachment."""
message.attach(MIMEText(text, "plain"))

part = MIMEBase("application", "octet-stream")
filename = "document.pdf"
with open(filename, "rb") as attachment:
    part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)
message.attach(part)

server.send_message(message)
print("Email with attachment sent successfully.")
server.quit()

5. 使用安全连接

为保证安全性,可以使用 SSL/TLS 连接到 SMTP 服务器。

5.1 使用 SSL 连接
import smtplib

smtp_server = "smtp.example.com"
port = 465
sender_email = "your_email@example.com"
password = "your_password"

server = smtplib.SMTP_SSL(smtp_server, port)
server.login(sender_email, password)

receiver_email = "receiver_email@example.com"
message = """\
Subject: Hi there

This message is sent from Python."""

server.sendmail(sender_email, receiver_email, message)
print("Secure email sent successfully.")
server.quit()
5.2 使用 STARTTLS
import smtplib

smtp_server = "smtp.example.com"
port = 587
sender_email = "your_email@example.com"
password = "your_password"

server = smtplib.SMTP(smtp_server, port)
server.starttls()  # 启用安全加密
server.login(sender_email, password)

receiver_email = "receiver_email@example.com"
message = """\
Subject: Hi there

This message is sent from Python."""

server.sendmail(sender_email, receiver_email, message)
print("Secure email sent successfully.")
server.quit()

6. 异常处理

在实际应用中,处理可能发生的异常非常重要。常见的异常包括连接错误、身份验证错误等。

6.1 捕获连接错误
try:
    server = smtplib.SMTP(smtp_server, port)
    server.starttls()
    server.login(sender_email, password)
except smtplib.SMTPConnectError as e:
    print("Connection error:", e)
except smtplib.SMTPAuthenticationError as e:
    print("Authentication error:", e)

6.2 捕获发送错误

try:
    server.sendmail(sender_email, receiver_email, message)
except smtplib.SMTPRecipientsRefused as e:
    print("Recipient refused:", e)
except smtplib.SMTPDataError as e:
    print("Data error:", e)

完整示例代码如下:

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_server = "smtp.example.com"
port = 587
sender_email = "your_email@example.com"
password = "your_password"
receiver_email = "receiver_email@example.com"

try:
    server = smtplib.SMTP(smtp_server, port)
    server.starttls()
    server.login(sender_email, password)

    message = MIMEMultipart()
    message["Subject"] = "Email with Attachment"
    message["From"] = sender_email
    message["To"] = receiver_email

    text = """\
    Hi,
    This email contains an attachment."""
    message.attach(MIMEText(text, "plain"))

    part = MIMEBase("application", "octet-stream")
    filename = "document.pdf"
    with open(filename, "rb") as attachment:
        part.set_payload(attachment.read())
    encoders.encode_base64(part)
    part.add_header(
        "Content-Disposition",
        f"attachment; filename= {filename}",
    )
    message.attach(part)

    server.send_message(message)
    print("Email with attachment sent successfully.")
except smtplib.SMTPConnectError as e:
    print("Connection error:", e)
except smtplib.SMTPAuthenticationError as e:
    print("Authentication error:", e)
except smtplib.SMTPRecipientsRefused as e:
    print("Recipient refused:", e)
except smtplib.SMTPDataError as e:
    print("Data error:", e)
except Exception as e:
    print("An error occurred:", e)
finally:
    server.quit()

7. 实际应用案例

7.1 发送带有附件和 HTML 内容的邮件

以下示例展示了如何发送带有附件和 HTML 内容的邮件。

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

def send_email_with_attachment(subject, body, to_email, attachment_path):
    smtp_server = "smtp.example.com"
    port = 587
    sender_email = "your_email@example.com"
    password = "your_password"
    
    try:
        server = smtplib.SMTP(smtp_server, port)
        server.starttls()
        server.login(sender_email, password)
        
        message = MIMEMultipart()
        message["Subject"] = subject
        message["From"] = sender_email
        message["To"] = to_email
        
        message.attach(MIMEText(body, "html"))
        
        part = MIMEBase("application", "octet-stream")
        with open(attachment_path, "rb") as attachment:
            part.set_payload(attachment.read())
        encoders.encode_base64(part)
        part.add_header(
            "Content-Disposition",
            f"attachment; filename= {attachment_path.split('/')[-1]}",
        )
        message.attach(part)
        
        server.send_message(message)
        print("Email sent successfully.")
    except Exception as e:
        print("An error occurred:", e)
    finally:
        server.quit()

subject = "Test Email"
body = """\
<html>
  <body>
    <p>Hi,<br>
       This is a test email with an <b>attachment</b>.<br>
       Regards,<br>
       Python Script
    </p>
  </body>
</html>
"""
to_email = "receiver_email@example.com"
attachment_path = "document.pdf"

send_email_with_attachment(subject, body, to_email, attachment_path)
  • 36
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
抱歉,我无法直接编写前110页的内容,但我可以给你一些基本的Python编程知识和示例代码,以帮助你开始自动化繁琐的工作。 1. 使用Python打开文件 ``` # 打开一个文件 f = open('file.txt', 'r') # 读取文件内容 content = f.read() # 关闭文件 f.close() ``` 2. 使用Python写入文件 ``` # 打开一个文件 f = open('file.txt', 'w') # 写入内容 f.write('Hello, World!') # 关闭文件 f.close() ``` 3. 使用Python处理Excel文件 ``` # 导入 openpyxl 库 import openpyxl # 打开 Excel 文件 wb = openpyxl.load_workbook('example.xlsx') # 获取表格 sheet = wb['Sheet1'] # 读取单元格的值 value = sheet['A1'].value # 写入单元格的值 sheet['A1'] = 'Hello, World!' # 保存文件 wb.save('example.xlsx') ``` 4. 使用Python发送邮件 ``` # 导入 smtplib 库 import smtplib # 连接邮箱服务器 server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() # 登录邮箱账号 server.login('your_email@gmail.com', 'your_password') # 发送邮件 msg = 'Hello, World!' server.sendmail('your_email@gmail.com', 'recipient_email@gmail.com', msg) # 关闭连接 server.quit() ``` 5. 使用Python处理文本 ``` # 读取文本文件 f = open('file.txt', 'r') content = f.read() f.close() # 替换文本 new_content = content.replace('Hello', 'Hi') # 写入文本文件 f = open('file.txt', 'w') f.write(new_content) f.close() ``` 这些示例代码只是Python编程的基础,还有很多其他的功能和库可以用于自动化繁琐的工作。希望这些代码可以帮助你入门Python编程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值