Python 通过电子邮件发送 pdf 得到意外的关键字参数 'main_type'

Python emailing pdf getting unexpected keyword argument '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)

您有一些拼写错误 - 只需将 main_type 更改为 maintype 并将 file_name 更改为 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