Enzo Vidal
Enzo Vidal

Reputation: 249

TypeError: cannot concatenate 'str' and 'list' objects in email

I am working on sending an email in python. Right now, I want to send entries from a list via email but I am encountering an error saying "TypeError: cannot concatenate 'str' and 'list' objects" and I have no idea to debug it. The following is the code that I have. I'm still new in this language (3 weeks) so I have a little backgroud.

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()

Upvotes: 16

Views: 62257

Answers (2)

Irshad Bhat
Irshad Bhat

Reputation: 8709

Problem is that in the code line msg = header + x, the name header is a string and x is a list so these two cannot be concatenated using + operator. The solution is to convert x to a string. One way of doing that is to extract elements from the list, convert them to str and .join() them together. So you should replace the code line:

msg = header + x

by:

msg = header + "".join([str(i) for i in x])

Upvotes: 5

David Sanders
David Sanders

Reputation: 4129

The problem is with msg = header + x. You're trying to apply the + operator to a string and a list.

I'm not exactly sure how you want x to be displayed but, if you want something like "[1, 2, 3]", you would need:

msg = header + str(x)

Or you could do,

msg = '{header}{lst}'.format(header=header, lst=x)

Upvotes: 36

Related Questions