我正在使用python发送电子邮件。现在,我想通过电子邮件从列表中发送条目,但是遇到一个错误,提示“ TypeError:无法连接'str'和'list'对象”,我不知道要对其进行调试。以下是我的代码。我还是这个语言的新手(3周),所以有点背景知识。
import smtplib
x = [2, 3, 4] #list that I want to send
to = '' #Recipient
user_name = '' #Sender username
user_pwrd = '' #Sender Password
smtpserver = smtplib.SMTP("mail.sample.com",port)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login(user_name,user_pwrd)
#Header Part of the Email
header = 'To: '+to+'\n'+'From: '+user_name+'\n'+'Subject: \n'
print header
#Msg
msg = header + x #THIS IS THE PART THAT I WANT TO INSERT THE LIST THAT I WANT TO SEND. the type error occurs in this line
#Send Email
smtpserver.sendmail(user_name, to, msg)
print 'done!'
#Close Email Connection
smtpserver.close()
问题出在哪里msg = header + x
。您正在尝试将+
运算符应用于字符串和列表。
我不确定您要如何x
显示,但是,如果您想要类似“ [1、2、3]”的内容,则需要:
msg = header + str(x)
或者你可以做
msg = '{header}{lst}'.format(header=header, lst=x)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句