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

使用Python的MIMEApplication()将JSON文件作为邮件附件发送

发布时间:2023-12-24 23:44:16

使用Python的MIMEApplication()可以将JSON文件作为邮件附件发送。以下是一个例子:

首先,我们需要导入相应的模块和函数:

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

然后,我们需要设置发件人、收件人和邮件主题:

sender = "sender@example.com"
receiver = "receiver@example.com"
subject = "JSON attachment"

接下来,我们需要创建一个MIMEMultipart对象,并设置邮件的发件人、收件人和主题:

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

然后,我们需要打开要作为附件的JSON文件,并将其读取为字符串:

filename = "data.json"
with open(filename, "r") as file:
    data = file.read()

接下来,我们需要创建一个MIMEApplication对象,将JSON字符串设置为其主体:

attachment = MIMEApplication(data)

然后,我们需要设置附件的相关属性,包括文件名和Content-Disposition头部:

attachment.add_header("Content-Disposition", "attachment", filename=filename)

最后,我们将附件添加到MIMEMultipart对象中,并发送邮件:

msg.attach(attachment)

try:
    smtpObj = smtplib.SMTP("smtp.example.com", 25)
    smtpObj.sendmail(sender, receiver, msg.as_string())
    print("邮件发送成功")
except smtplib.SMTPException:
    print("Error: 无法发送邮件")

完整的例子如下所示:

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

sender = "sender@example.com"
receiver = "receiver@example.com"
subject = "JSON attachment"

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

filename = "data.json"
with open(filename, "r") as file:
    data = file.read()

attachment = MIMEApplication(data)
attachment.add_header("Content-Disposition", "attachment", filename=filename)

msg.attach(attachment)

try:
    smtpObj = smtplib.SMTP("smtp.example.com", 25)
    smtpObj.sendmail(sender, receiver, msg.as_string())
    print("邮件发送成功")
except smtplib.SMTPException:
    print("Error: 无法发送邮件")

请注意,你需要将sender@example.comreceiver@example.com替换为实际的发件人和收件人的邮件地址,将smtp.example.com替换为实际的SMTP服务器地址。此外,你还需要保证本地存在名为data.json的JSON文件。

以上是使用Python的MIMEApplication()将JSON文件作为邮件附件发送的示例。