首页 > 解决方案 > Python通过电子邮件发送pdf得到意外的关键字参数'main_type'

问题描述

我正在尝试附加 pdf 并在 python 中发送电子邮件。低于错误 -

TypeError:set_bytes_content() 得到了一个意外的关键字参数“main_type”。

新手在这里,不知道我做错了什么?

import os
import smtplib
from email.message import EmailMessage
import PyPDF2


EMAIL_ADDRESS = os.environ.get('EMAIL_USER')
EMAIL_PASSWORD = os.environ.get('EMAIL_PASS')

msg = EmailMessage()
msg['Subject'] = 'EDs Diet Plan'
msg['From'] = EMAIL_ADDRESS
msg['To'] = 'test@gmail.com'  
msg.set_content('Please find attached your customized diet plan and the general list of foods')

file = 'LFV Diet.pdf'

with open(file, 'rb') as f:
    file_data = f.read()
    #file_type =
    file_name = f.name

msg.add_attachment(file_data, main_type='application', subtype='octet-stream', file_name=file_name)

with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
    smtp.send_message(msg)

标签: pythonemailsmtpsmtplib

解决方案


您有一些拼写错误 - 只需更改main_typemaintypefile_nameto filename

前:

msg.add_attachment(file_data, main_type='application', subtype='octet-stream', file_name=file_name)

后:

msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)

一些很好的例子在这里 - https://docs.python.org/3/library/email.examples.html


推荐阅读