对象没有“encode”属性

2024-05-23 22:33:30 发布

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

我正试图在我的电子邮件中附加一个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()

有没有其他方法可以发送附加文件和正文消息?


Tags: thecomyoumessageexample解决方案xlsxresults
1条回答
网友
1楼 · 发布于 2024-05-23 22:33:30

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 822email格式的字符串)。

相关问题 更多 >