对象没有属性 'encode'

Object has no attribute 'encode'

我正在尝试将 xlsx 文件附加到我的电子邮件中。我查找了解决方案,它涉及使用 email.encoders。但是当我使用这个解决方案时,我得到了一个错误。我正在使用其他人有效的解决方案。

File "C:\Documents and Settings\Desktop\AppTera\dev\MTC_test\MTC_sender.py", line 41, in sendmail
    s.sendmail(FROMADDR, TOADDR, message.as_string())
AttributeError: 'list' object has no attribute 'encode'
def sendmail():
      SERVER = 'server.com'
      FROMADDR = "joe@example.com"
      TOADDR = ['bob@example.com']
      CCADDR = ['bill@example.com']

      message = MIMEMultipart('mixed')
      message['From'] = FROMADDR
      message['To'] = TOADDR
      message['Subject'] = "Reporting for IVR Application"

      BODY = "Hello Angela,\n\nI'm attaching the reports for %s/%s. These   are the same reports\
 you have requested in the past.\n\nPlease let me know if you need any additional reports.\n\n\
 Thank you"% (str(MONTH), str(YEAR))
      message.attach(MIMEText(BODY, 'plain'))

      filename = "results.csv.xlsx"
      path = r'C:\Documents and  Settings\Desktop\MonthlyReports\MTC\%s_%s' % (str(YEAR), str(MONTH))
      os.chdir(path)
      fileMsg = MIMEBase('application', 'xlsx')
      fileMsg.set_payload(open('results.csv.xlsx', 'rb').read())
      encoders.encode_base64(fileMsg)
      fileMsg.add_header('Content-Disposition','attachment;filename=results.csv.xls')
      message.attach(fileMsg)


      s = smtplib.SMTP(SERVER, 25)
      s.set_debuglevel(1)
      s.sendmail(FROMADDR, TOADDR, message.as_string())
      s.quit()

还有其他方法可以将附件与正文消息一起发送吗?

s 是您由 s = smtplib.SMTP(SERVER, 25) 创建的 SMTP 对象。所以 s.sendmail(FROMADDR, TOADDR, message.as_string()) 的参数应该根据 documentation.

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])

Send mail. The required arguments are an RFC 822 from-address string, a list of RFC 822 to-address strings (a bare string will be treated as a list with 1 address), and a message string. The caller may pass a list of ESMTP options (such as 8bitmime) to be used in MAIL FROM commands as mail_options. ESMTP options (such as DSN commands) that should be used with all RCPT commands can be passed as rcpt_options. (If you need to use different ESMTP options to different recipients you have to use the low-level methods such as mail(), rcpt() and data() to send the message.)

确保 FROMADDR 是字符串(不是列表),TOADDR 应该是字符串或字符串列表(RFC 822 电子邮件格式字符串)。

我知道这个帖子已经过时了,但我为此焦头烂额,希望有同样经历的人能找到这个帖子。

当您使用 MIME Multipart 容器时,它不同于使用标准 smtplib 发送它。

您可以这样定义收件人列表:

RECIPIENTS = ['abc@abc.com', 'xyz@xyz.com']

那么消息['To']的格式应该是这样的:

msg['To'] = ', '.join(RECIPIENTS)

最终目的地的代码块返回到列表而不是字符串

#Provide the contents of the email.
    response = client.send_raw_email(
        Source=msg['From'],
        Destinations=['abc@abc.com', 'xyz@xyz.com'],
        RawMessage={
            'Data':msg.as_string(),
        },
#        ConfigurationSetName=CONFIGURATION_SET
    )

这可能不是最干净的答案,但希望它能帮助到别人。