TypeError:“method”类型的对象没有len();正在尝试将文件附加到电子邮件消息

2024-06-26 03:06:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3,我试图在电子邮件中附加一个文件。我对MIME和SMTP很陌生。 这就是我的功能:

def func():
path = mypath
for file in glob.glob(path + "\\happy*"):
    print(file)
    sender = myemail
    senderto = someonesemail
    msg = MIMEMultipart('alternative')
    msg['Subject'] = 'The File'
    msg['From'] = sender
    msg['To'] = senderto
    body = "File"
    msg.attach(MIMEText(body, 'plain'))
    part = MIMEBase('application', 'octet-stream')
    part.set_payload(open(file, encoding='charmap').read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', "attachment; filename= %s" % file)
    msg.attach(part)
    global smtpSettings
    smtpSettings = smtplib.SMTP(host=myhost, port=587)
    print("Step 1 Complete")
    smtpSettings.login(smtpusername, smtppassword)
    print("Step 2 Complete")
    smtpSettings.sendmail(sender, senderto, msg.as_string)
    print("Step 3 Complete")
    smtpSettings.quit()
    print("Success")

旁注:senderto=接收方。 我得到的输出是:

^{pr2}$

Tags: pathstepbodymsgsmtpglobsenderfile
2条回答

我是yagmail的维护者,这是一个包,它使发送电子邮件(带附件或不带附件)变得更加容易。在

import yagmail
yag = yagmail.SMTP(myemail, 'mypassword')
yag.send(to = someonesemail, subject = 'The File', contents = ['File', file])

发送电子邮件只需要三行。不错!在

内容将巧妙地猜测file变量字符串指向一个文件,并因此附加该文件。在

完整代码可能是:

^{2}$

在步骤3中修复,更改

smtpSettings.sendmail(sender, senderto, msg.as_string)

^{2}$

因为as_string是一种方法

相关问题 更多 >