首页 > 编程知识 正文

如何使用Python发送电子邮件

时间:2023-11-19 08:53:29 阅读:296085 作者:ABTO

Python提供了强大的库和模块,使我们能够轻松地发送电子邮件。无论是发送简单的文本邮件还是包含附件和HTML内容的复杂邮件,Python都能够满足我们的需求。本文将详细介绍如何使用Python发送电子邮件。

一、准备工作

在开始发送电子邮件之前,我们需要做一些准备工作。

首先,确保你已经安装了Python的SMTP(Simple Mail Transfer Protocol)模块。该模块提供了发送邮件的功能。你可以使用以下命令安装SMTP模块:

pip install secure-smtplib

接下来,你需要获取发送邮件所需的SMTP服务器信息。不同的邮箱服务商有不同的SMTP服务器地址和端口号。例如,Gmail的SMTP服务器地址是smtp.gmail.com,端口号是587。你还需要有一个邮箱账号和密码用于登录SMTP服务器。

现在我们已经完成了准备工作,可以开始编写Python代码发送电子邮件了。

二、发送纯文本邮件

首先,我们来发送一个简单的纯文本邮件。

Python提供了smtplib模块,我们可以使用它来连接SMTP服务器并发送邮件。以下是一个发送纯文本邮件的示例代码:

import smtplib
from email.mime.text import MIMEText

def send_email():
    sender = 'your_email@example.com'  # 发件人邮箱
    password = 'your_password'  # 发件人邮箱密码
    receiver = 'recipient_email@example.com'  # 收件人邮箱
    subject = 'Hello from Python!'  # 邮件主题
    content = 'This is a test email from Python.'  # 邮件内容

    msg = MIMEText(content)
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = receiver

    try:
        smtp_server = smtplib.SMTP('smtp.gmail.com', 587)  # 连接SMTP服务器
        smtp_server.starttls()  # 启用TLS加密
        smtp_server.login(sender, password)  # 登录SMTP服务器
        smtp_server.sendmail(sender, receiver, msg.as_string())  # 发送邮件
        print('Email sent successfully.')
    except Exception as e:
        print('Failed to send email:', str(e))
    finally:
        smtp_server.quit()  # 关闭SMTP服务器连接

send_email()

在这段代码中,我们首先引入了smtplib模块和email.mime.text模块,分别用于连接SMTP服务器和创建纯文本邮件。

然后,我们定义了一个send_email函数,在函数中设置了发件人邮箱、收件人邮箱、邮件主题和邮件内容。我们使用MIMEText类创建一个MIMEText对象,并将邮件主题、发件人邮箱和收件人邮箱添加到MIMEText对象的对应属性中。

接下来,我们连接到SMTP服务器并启用TLS加密。然后,使用发件人邮箱和密码登录SMTP服务器,并调用sendmail方法发送邮件。最后,我们关闭SMTP服务器连接。

运行该代码,你将收到一封来自Python的测试邮件。

三、发送带附件的邮件

接下来,我们来发送一个带附件的邮件。

Python提供了email.mime.multipart模块,我们可以使用它来创建带附件的邮件。以下是一个发送带附件邮件的示例代码:

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

def send_email_with_attachment():
    sender = 'your_email@example.com'  # 发件人邮箱
    password = 'your_password'  # 发件人邮箱密码
    receiver = 'recipient_email@example.com'  # 收件人邮箱
    subject = 'Hello from Python!'  # 邮件主题
    content = 'This is a test email from Python.'  # 邮件内容
    attachment_path = 'path/to/attachment.pdf'  # 附件路径

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = receiver

    # 添加邮件正文
    msg.attach(MIMEText(content))

    # 添加附件
    attachment = MIMEApplication(open(attachment_path, 'rb').read())
    attachment.add_header('Content-Disposition', 'attachment', filename='attachment.pdf')
    msg.attach(attachment)

    try:
        smtp_server = smtplib.SMTP('smtp.gmail.com', 587)  # 连接SMTP服务器
        smtp_server.starttls()  # 启用TLS加密
        smtp_server.login(sender, password)  # 登录SMTP服务器
        smtp_server.sendmail(sender, receiver, msg.as_string())  # 发送邮件
        print('Email sent successfully.')
    except Exception as e:
        print('Failed to send email:', str(e))
    finally:
        smtp_server.quit()  # 关闭SMTP服务器连接

send_email_with_attachment()

在这段代码中,我们引入了email.mime.multipart模块和email.mime.application模块,分别用于创建带附件的邮件和添加附件。

我们创建了一个MIMEMultipart对象,并将邮件主题、发件人邮箱和收件人邮箱添加到MIMEMultipart对象的对应属性中。然后,我们使用MIMEText类创建一个MIMEText对象,并将邮件正文添加到MIMEMultipart对象中。接着,我们使用MIMEApplication类创建一个MIMEApplication对象,并将附件文件内容添加到MIMEApplication对象中,同时设置附件的文件名和Content-Disposition属性。最后,我们将附件添加到MIMEMultipart对象中。

运行该代码,你将收到一封带有附件的测试邮件。

四、发送HTML格式的邮件

除了发送纯文本和带附件的邮件,还可以发送HTML格式的邮件。

Python提供了email.mime.text模块,我们可以使用它来创建HTML格式的邮件。以下是一个发送HTML邮件的示例代码:

import smtplib
from email.mime.text import MIMEText

def send_html_email():
    sender = 'your_email@example.com'  # 发件人邮箱
    password = 'your_password'  # 发件人邮箱密码
    receiver = 'recipient_email@example.com'  # 收件人邮箱
    subject = 'Hello from Python!'  # 邮件主题
    content = '

This is a test email from Python.

It contains HTML content.

' # 邮件内容 msg = MIMEText(content, 'html') msg['Subject'] = subject msg['From'] = sender msg['To'] = receiver try: smtp_server = smtplib.SMTP('smtp.gmail.com', 587) # 连接SMTP服务器 smtp_server.starttls() # 启用TLS加密 smtp_server.login(sender, password) # 登录SMTP服务器 smtp_server.sendmail(sender, receiver, msg.as_string()) # 发送邮件 print('Email sent successfully.') except Exception as e: print('Failed to send email:', str(e)) finally: smtp_server.quit() # 关闭SMTP服务器连接 send_html_email()

在这段代码中,我们创建了一个MIMEText对象,并将邮件主题、发件人邮箱和收件人邮箱添加到MIMEText对象的对应属性中。我们还指定了MIMEText对象的第二个参数为'html',表示该邮件是HTML格式的。然后,我们将HTML内容添加到MIMEText对象中。

运行该代码,你将收到一封包含HTML内容的测试邮件。

五、总结

本文介绍了如何使用Python发送电子邮件。我们首先讲解了发送纯文本邮件的方法,然后介绍了发送带附件的邮件和发送HTML格式的邮件的方法。通过这些示例代码,你可以轻松实现各种复杂的邮件发送需求。

希望本文能够帮助你学会使用Python发送电子邮件。如果你有任何问题或疑惑,可以随时在下方留言。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。