TypeError: object of type 'method' has no len() | Trying to attach file to email msg

TypeError: object of type 'method' has no len() | Trying to attach file to email msg

我正在使用 Python 3,我正在尝试将文件附加到电子邮件中。我在 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 = receiver。 我得到的输出是:

Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
    return self.func(*args)
  File "C:/Users/Luis/Desktop/PYTHON/smtptestes.py", line 73, in func
    smtpSettings.sendmail(sender, senderto, msg.as_string)
  File "C:\Python34\lib\smtplib.py", line 769, in sendmail
    esmtp_opts.append("size=%d" % len(msg))
TypeError: object of type 'method' has no len()

在步骤 3 中修复,更改

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

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

因为as_string是一个方法

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

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

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

内容会很聪明地猜测file变量字符串指向一个文件,从而附加文件。

完整代码可能是:

import yagmail
import glob

def func(path, user, pw, ):        
    subject = 'The File' 
    body = "File"  
    yag = yagmail.SMTP(user, pw, host = myhost)
    for fname in glob.glob(path + "\happy*"): 
        yag.send(someonesemail, subject, [body, fname])

 func(mypath, smtpusername, smtppassword)