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

在Python中发送带附件的电子邮件

发布时间:2024-01-12 18:25:41

在Python中发送带附件的电子邮件可以使用smtplib模块来实现。以下是一个带附件的电子邮件发送的示例代码:

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

# 邮件发送方的信息
sender_email = "your_email@example.com"
sender_password = "your_password"

# 邮件接收方的信息
receiver_email = "receiver_email@example.com"

# 创建一个带附件的邮件实例
message = MIMEMultipart()
message["Subject"] = "带附件的邮件示例"
message["From"] = sender_email
message["To"] = receiver_email

# 添加邮件正文
message.attach(MIMEText("这是一封带附件的邮件,请查收!", "plain"))

# 添加附件
attachment_path = "path_to_attachment_file"
with open(attachment_path, "rb") as attachment_file:
    attachment = MIMEApplication(attachment_file.read(), "octet-stream")
    attachment.add_header("Content-Disposition", "attachment", filename="attachment_file_name")
    message.attach(attachment)

# 链接SMTP服务器并发送邮件
try:
    # 连接SMTP服务器
    smtp_server = smtplib.SMTP("smtp.gmail.com", 587)  # 使用Gmail SMTP服务器作为示例
    smtp_server.starttls()

    # 登录SMTP服务器
    smtp_server.login(sender_email, sender_password)

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

    # 断开与SMTP服务器的连接
    smtp_server.quit()
    print("邮件已发送成功!")

except Exception as e:
    print("邮件发送失败:" + str(e))

以上代码中,我们首先导入了需要的模块,然后设置了邮件发送方和接收方的信息。接着创建了一个带附件的邮件实例,并设置了邮件的主题、发送方和接收方等信息。然后添加了邮件的正文和附件。最后,通过链接SMTP服务器并登录,发送邮件。

需要注意的是,我们使用了Gmail SMTP服务器作为示例,你需要替换为你自己的SMTP服务器地址和端口。另外,你需要提供发送方的邮箱地址和密码,并将附件的路径和文件名替换为你自己的附件信息。

希望以上示例能对你理解如何在Python中发送带附件的电子邮件有所帮助!