欢迎访问宙启技术站
智能推送

Python编写邮件发送程序

发布时间:2023-12-04 16:25:22

发送邮件是一种常见的需求,无论是用于工作还是个人用途。Python提供了多种方式来编写邮件发送程序,本文将以使用smtplib库为例,介绍如何编写邮件发送程序,并附上使用例子。

# 一、准备工作

在编写邮件发送程序之前,我们需要进行一些准备工作。

1. 安装smtplib库

smtplib库是Python内置的邮件发送库,我们可以使用pip工具来安装它。打开命令行窗口,执行以下命令:

pip install smtplib

2. 准备发件人和收件人的邮箱账号及密码

编写邮件发送程序时,我们需要提供发件人和收件人的邮箱账号及密码。请确保这些信息是准备好的。

# 二、编写邮件发送程序

下面是一个使用smtplib库编写的简单的邮件发送程序。

import smtplib
from email.mime.text import MIMEText

def send_mail(sender, receiver, subject, message, password):
    # 创建邮件的MIMEText对象
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = receiver
    
    try:
        # 连接到SMTP服务器
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        # 登录到邮箱账号
        server.login(sender, password)
        # 发送邮件
        server.sendmail(sender, receiver, msg.as_string())
        # 关闭连接
        server.quit()
        print("邮件发送成功")
    except Exception as e:
        print("邮件发送失败:", e)

# 使用例子
sender = 'your_email@gmail.com'
receiver = 'recipient_email@gmail.com'
subject = 'Hello, World!'
message = 'This is a test email from Python.'
password = 'your_email_password'

send_mail(sender, receiver, subject, message, password)

# 三、使用例子

在实际应用中,我们可以根据需要修改send_mail函数的参数,具体发送什么样的邮件内容。下面是一个使用例子,我们将发送一封HTML格式的邮件,并添加一个附件(PDF文件)。

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

def send_mail(sender, receiver, subject, message, password, attachment_path):
    # 创建邮件的MIMEMultipart对象
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = receiver
    
    # 添加邮件正文
    msg.attach(MIMEText(message, 'html'))
    
    # 添加附件
    with open(attachment_path, 'rb') as f:
        attachment = MIMEApplication(f.read())
        attachment.add_header('Content-Disposition',
                              'attachment',
                              filename=attachment_path.split('/')[-1])
        msg.attach(attachment)
    
    try:
        # 连接到SMTP服务器
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        # 登录到邮箱账号
        server.login(sender, password)
        # 发送邮件
        server.sendmail(sender, receiver, msg.as_string())
        # 关闭连接
        server.quit()
        print("邮件发送成功")
    except Exception as e:
        print("邮件发送失败:", e)

# 使用例子
sender = 'your_email@gmail.com'
receiver = 'recipient_email@gmail.com'
subject = 'Hello, World!'
message = '<h1>This is a test email from Python.</h1>'
password = 'your_email_password'
attachment_path = 'path_to_your_attachment.pdf'

send_mail(sender, receiver, subject, message, password, attachment_path)

在上述例子中,我们使用MIMEText创建了一封HTML格式的邮件,并使用MIMEApplication添加了一个附件(PDF文件)。你可以根据需要修改邮件的内容和附件的路径。

# 结论

Python提供了多种方式来编写邮件发送程序,使用smtplib库是其中一种方式。本文介绍了如何使用smtplib库来编写邮件发送程序,并提供了两个例子:一个发送纯文本邮件,另一个发送HTML格式邮件,并添加附件。通过修改参数,你可以根据需要定制自己的邮件发送程序。