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

用Python编写一个简单的邮件发送程序

发布时间:2023-12-04 10:51:50

邮件发送是一种常见的通信方式,Python 提供了 smtplib 模块来实现发送电子邮件的功能。下面是一个使用 Python 编写的简单邮件发送程序的示例,包括创建邮件对象、连接邮件服务器、登录邮件账户、设置邮件主题和正文、添加附件、发送邮件等步骤。

示例代码如下:

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(sender_email, sender_password, receiver_email, subject, body, attachment_path=None):
    # 创建邮件对象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject
    
    # 添加邮件正文
    msg.attach(MIMEText(body, 'plain'))
    
    if attachment_path:
        # 添加附件
        attachment = open(attachment_path, 'rb')
        part = MIMEBase('application', 'octet-stream')
        part.set_payload((attachment).read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', "attachment; filename= %s" % attachment_path.split('/')[-1])
        msg.attach(part)

    # 连接邮件服务器
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(sender_email, sender_password)
    
        # 发送邮件
        server.send_message(msg)
        server.quit()
        print("邮件发送成功!")
    except Exception as e:
        print("邮件发送失败:", e)


sender_email = "your_email@gmail.com"
sender_password = "your_email_password"
receiver_email = "recipient_email@gmail.com"
subject = "邮件发送测试"
body = "这是一封来自 Python 的测试邮件,带有附件。"
attachment_path = "path_to_your_attachment/file.txt"

send_email(sender_email, sender_password, receiver_email, subject, body, attachment_path)

上述示例程序使用了 smtplib 模块提供的 SMTP 类来连接邮件服务器,并使用 email 模块提供的类来创建邮件对象。该程序首先创建一个 MIMEMultipart 对象用于存储邮件内容,然后设置发送者和接收者的 email 地址、邮件主题和正文。如果指定了附件路径,可以通过 MIMEBase 类添加附件并设置附件的文件名,然后将附件添加到邮件对象中。

最后,使用 SMTP 类的 starttls() 方法将通信协议切换为 TLS 加密,并调用 login() 方法登录邮件账户。最后,使用 send_message() 方法发送邮件,关闭连接。

要运行上述示例,您需要将 your_email@gmail.com 替换为您的发送者邮箱地址,your_email_password 替换为您的邮箱密码。同时,将 recipient_email@gmail.com 替换为您要发送给的接收者邮箱地址。如果要发送附件,请将 path_to_your_attachment/file.txt 替换为附件的路径。

请注意,如果您使用的是 Gmail 邮箱,则需要将程序的 SMTP 服务器更改为 smtp.gmail.com,并将端口更改为 587

希望以上示例对您有所帮助!