Python 3 – 使用SMTP发送电子邮件

Python 3 – 使用SMTP发送电子邮件

前言

在日常工作和生活中,我们经常需要发送电子邮件进行沟通和交流。Python 3 中内置的smtplib模块提供了很好的支持,可以方便地使用SMTP协议发送电子邮件。

基本概念

在开始之前,我们需要了解几个基本概念。

  1. SMTP(Simple Mail Transfer Protocol) – 简单邮件传输协议,用于发送电子邮件。
  2. MIME(Multipurpose Internet Mail Extensions) – 多用途互联网邮件扩展,用于在邮件中添加各种附件。
  3. 端口号 – 发送电子邮件需要使用SMTP服务器和对应的端口号。

发送简单文本邮件

让我们从一个简单的例子开始,使用SMTP发送一封文本邮件。

import smtplib

# SMTP服务器信息
smtp_server = "smtp.gmail.com"
smtp_port = 587

# 发件人信息
sender_email = "your_email@gmail.com"
sender_password = "your_password"

# 收件人信息
receiver_email = "receiver_email@example.com"

# 邮件内容
subject = "Python 3 - SMTP发送电子邮件"
body = "Hello, world!"

# 创建SMTP连接
smtp_conn = smtplib.SMTP(smtp_server, smtp_port)
smtp_conn.starttls()
smtp_conn.login(sender_email, sender_password)

# 构造邮件
message = f"""\
From: {sender_email}
To: {receiver_email}
Subject: {subject}

{body}
"""

# 发送邮件
smtp_conn.sendmail(sender_email, receiver_email, message)

# 断开SMTP连接
smtp_conn.quit()

在上面的代码中,我们使用Gmail SMTP服务器发送了一封文本邮件,其中smtp_server为Gmail SMTP服务器地址,smtp_port为对应的端口号,sender_email和sender_password是发送人的邮箱和密码,receiver_email是接收人的邮箱地址,subject和body是邮件主题和内容。在代码中,我们首先创建SMTP连接,使用starttls()方法启用TLS安全连接,并通过login()方法进行邮箱账户验证。接着我们构造了邮件,包括邮件头信息和邮件内容。最后使用sendmail()方法将邮件发送到接收人邮箱。

发送带HTML格式的邮件

除了纯文本邮件外,我们还可以使用HTML格式的邮件进行信息传输。下面是一个简单例子,发送了一封带HTML格式的邮件。

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

# SMTP服务器信息
smtp_server = "smtp.gmail.com"
smtp_port = 587

# 发件人信息
sender_email = "your_email@gmail.com"
sender_password = "your_password"

# 收件人信息
receiver_email = "receiver_email@example.com"

# 邮件内容
subject = "Python 3 - SMTP发送电子邮件"
body = """\
<html>
  <head></head>
  <body>
    <p>Hello, world!<br>
       How are you today?<br>
       Here is the <a href="https://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""

# 创建MIMEMultipart对象,并添加MIMEText内容
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message.attach(MIMEText(body, "html"))

# 创建SMTP连接
smtp_conn = smtplib.SMTP(smtp_server, smtp_port)
smtp_conn.starttls()
smtp_conn.login(sender_email, sender_password)

# 发送邮件
smtp_conn.sendmail(sender_email, receiver_email, message.as_string())

# 断开SMTP连接
smtp_conn.quit()

在上面的代码中,我们使用了email模块中的MIMEText和MIMEMultipart对象创建邮件。我们首先构造了body内容,使用了HTML标记来设置邮件格式。接着使用MIMEMultipart对象创建邮件内容,并将MIMEText作为附件添加到邮件中。最后发送邮件时使用message.as_string()将MIMEMultipart对象转换为字符串。

发送带附件的邮件

最后,我们展示了一个带有附件的邮件发送例子。这里我们使用了email模块中的MIMEBase和MIMEApplication对象。

import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email import encoders

# SMTP服务器信息
smtp_server = "smtp.gmail.com"
smtp_port = 587

# 发件人信息
sender_email = "your_email@gmail.com"
sender_password = "your_password"

# 收件人信息
receiver_email = "receiver_email@example.com"

# 邮件内容
subject = "Python 3 - SMTP发送电子邮件"
body = "有一个新的附件"

# 创建MIMEMultipart对象,并添加邮件内容
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message.attach(MIMEApplication(open("attachment.txt", "rb").read()))

# 发送邮件
try:
    # 创建SMTP连接
    smtp_conn = smtplib.SMTP(smtp_server, smtp_port)
    smtp_conn.starttls()
    smtp_conn.login(sender_email, sender_password)

    # 发送邮件
    smtp_conn.sendmail(sender_email, receiver_email, message.as_string())
except Exception as e:
    print(f"邮件发送失败: {e}")
else:
    print("邮件发送成功")

# 断开SMTP连接
smtp_conn.quit()

在上面的代码中,我们使用了open()方法来打开文件并读取文件内容,使用了MIMEApplication对象作为附件添加到邮件中。注意,我们需要设置附件的Content-Disposition参数为attachmen,这样邮件客户端才会识别附件并将其作为文件下载。在发送邮件时,我们首先使用try/except结构捕获错误,最后如果邮件成功发送,我们将显示“邮件发送成功”的信息。

结论

在本文中,我们学习了Python 3中使用SMTP发送电子邮件的基本知识和代码实现。我们实现了发送简单文本邮件、发送带HTML格式的邮件和发送带附件的邮件。通过这些例子,我们可以清楚地了解,使用Python发送电子邮件是一件非常简单和方便的事情。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程