我正在尝试将 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 = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5832373d183d20393528343d763b3735" rel="noreferrer noopener nofollow">[email protected]</a>"
TOADDR = ['<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="30525f52705548515d405c551e535f5d" rel="noreferrer noopener nofollow">[email protected]</a>']
CCADDR = ['<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d7dcd9d9f5d0cdd4d8c5d9d09bd6dad8" rel="noreferrer noopener nofollow">[email protected]</a>']
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 电子邮件格式字符串)。
关于python - 对象没有属性 'encode',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37730575/