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

Python中使用email.mime.application模块发送带有文本文件附件的邮件

发布时间:2024-01-02 02:02:16

在Python中,可以使用email.mime.application模块来发送带有文本文件附件的邮件。下面是一个使用例子:

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, receiver, subject, message, attachment_path):
    # 创建Multipart邮件对象
    msg = MIMEMultipart()
    msg["From"] = sender
    msg["To"] = receiver
    msg["Subject"] = subject

    # 添加正文内容
    body = MIMEText(message)
    msg.attach(body)

    # 添加附件
    with open(attachment_path, "rb") as attachment:
        attachment_part = MIMEApplication(attachment.read())
        attachment_part.add_header("Content-Disposition", "attachment", filename=attachment_path)
        msg.attach(attachment_part)

    # 发送邮件
    try:
        smtp = smtplib.SMTP("smtp.gmail.com", 587)  # 设置邮件服务器和端口
        smtp.ehlo()  # 进行SMTP服务器的握手操作
        smtp.starttls()  # 开启安全传输模式
        smtp.login(sender, "your_password")  # 登录邮箱
        smtp.sendmail(sender, receiver, msg.as_string())  # 发送邮件
        smtp.quit()  # 退出
        print("邮件发送成功!")
    except Exception as e:
        print("邮件发送失败:", str(e))

# 设置发件人、收件人和邮件主题
sender = "your_email@gmail.com"
receiver = "recipient_email@gmail.com"
subject = "Test Email with Attachment"

# 设置邮件正文和附件路径
message = "This is a test email with an attachment."
attachment_path = "path_to_your_attachment.txt"

# 发送邮件
send_email_with_attachment(sender, receiver, subject, message, attachment_path)

上面的代码中,我们使用MIMEMultipart类创建一个包含正文和附件的多部分邮件。正文部分使用MIMEText类创建,并附加到MIMEMultipart对象上。附件部分则是使用MIMEApplication类创建,并且需要设置Content-Disposition头部字段来指定附件的文件名。

在发送邮件时,我们使用smtplib库来连接到SMTP服务器并发送邮件。你需要将代码中的smtp.gmail.com587替换为你的邮件服务器的地址和端口号。另外,你也需要在smtp.login()方法中使用正确的发件人邮箱地址和密码来进行登录。

最后,我们调用send_email_with_attachment()函数并将发件人、收件人、主题、正文和附件路径作为参数传递给它,来发送邮件。

以上是一个简单的使用email.mime.application模块发送带有文本文件附件的邮件的例子。你可以根据自己的需求对代码进行修改和扩展。