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

Python中利用MIMEApplication()发送带有PPT文件附件的邮件

发布时间:2023-12-24 23:43:58

在Python中,我们可以使用MIMEApplication来发送带有PPT文件附件的邮件。下面是一个使用例子,该例子包括了如何创建一个带有PPT文件附件的邮件并发送。

首先,我们需要导入所需的模块:

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

然后,我们需要设置发送方和接收方的邮箱地址:

sender_email = "your_email@example.com"
receiver_email = "receiver_email@example.com"

接下来,我们需要创建一个带有PPT文件附件的邮件对象:

message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "PPT File Attachment"

然后,我们需要添加正文内容:

body = "This email contains a PPT file attachment."
message.attach(MIMEText(body, "plain"))

接下来,我们需要打开PPT文件并将其内容添加到邮件对象中:

with open("presentation.ppt", "rb") as file:
    attachment = MIMEApplication(file.read(), _subtype="ppt")
    attachment.add_header("content-disposition", "attachment", filename="presentation.ppt")
    message.attach(attachment)

最后,我们需要使用SMTP服务器发送邮件:

with smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls()
    server.login(sender_email, "your_password")
    server.sendmail(sender_email, receiver_email, message.as_string())

完整的代码如下所示:

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

sender_email = "your_email@example.com"
receiver_email = "receiver_email@example.com"

message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "PPT File Attachment"

body = "This email contains a PPT file attachment."
message.attach(MIMEText(body, "plain"))

with open("presentation.ppt", "rb") as file:
    attachment = MIMEApplication(file.read(), _subtype="ppt")
    attachment.add_header("content-disposition", "attachment", filename="presentation.ppt")
    message.attach(attachment)

with smtplib.SMTP("smtp.gmail.com", 587) as server:
    server.starttls()
    server.login(sender_email, "your_password")
    server.sendmail(sender_email, receiver_email, message.as_string())

请注意,你需要将your_email@example.com替换为你自己的发件人邮箱地址,receiver_email@example.com替换为你自己的收件人邮箱地址,presentation.ppt替换为你自己的PPT文件路径,your_password替换为你的邮箱密码。

这样,你就可以使用Python中的MIMEApplication发送带有PPT文件附件的邮件了。