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

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

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

发送带有PDF附件的邮件在Python中可以使用MIMEApplication()方法来实现。下面是一个使用例子:

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

def send_email_with_attachment(sender, receiver, subject, message, file_path):
    # 创建一个带有附件的邮件实例
    msg = MIMEMultipart()
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = subject

    # 添加邮件正文
    msg.attach(MIMEText(message, 'plain'))

    # 读取附件文件并添加到邮件中
    with open(file_path, 'rb') as file:
        attachment = MIMEApplication(file.read(), _subtype="pdf")
        attachment.add_header('Content-Disposition', 'attachment', filename=file_path)
        msg.attach(attachment)

    # 发送邮件
    try:
        smtp_obj = smtplib.SMTP('smtp.server.com', 587)  # 请填写你的SMTP服务器信息
        smtp_obj.starttls()
        smtp_obj.login('username', 'password')  # 请填写你的邮箱账号和密码
        smtp_obj.sendmail(sender, receiver, msg.as_string())
        smtp_obj.quit()
        print('邮件发送成功')
    except Exception as e:
        print('邮件发送失败')
        print(e)

# 使用例子
sender = 'sender@example.com'
receiver = 'receiver@example.com'
subject = '邮件主题'
message = '这是一封带有附件的邮件'
file_path = 'attachment.pdf'

send_email_with_attachment(sender, receiver, subject, message, file_path)

在上面的例子中,我们首先创建一个邮件实例msg,并设置相关信息,如发件人、收件人、主题等。然后,我们使用MIMEText()方法给邮件添加了一个简单的文本正文。接下来,我们使用open()方法读取附件文件,并使用MIMEApplication()方法将附件内容添加到邮件中。我们通过添加_subtype="pdf"参数来指定附件的类型为PDF。最后,我们使用smtplib.SMTP()方法连接到SMTP服务器,并调用sendmail()方法发送邮件。

请注意,在使用上述例子发送邮件之前,你需要替换为你自己的SMTP服务器信息、邮箱账号和密码,并确保附件文件attachment.pdf存在。此外,你还需要安装所需的Python邮件库,如smtplibemail

希望这个例子能帮助你发送带有PDF附件的邮件。如果有任何问题,请随时提问!