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

I am working on sending email in python. Right now, I want to send entries from a list by email, but I ran into an error saying: "TypeError: cannot concatenate the str and list objects, and I have no idea about debugging them. Below is the code that I have. I'm still new to 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() 
+7
python
source share
2 answers

The problem is msg = header + x . You are trying to apply the + operator to a row and list.

I'm not quite sure how you want to display x , but if you need something like "[1, 2, 3]", you will need:

 msg = header + str(x) 

Or you could do

 msg = '{header}{lst}'.format(header=header, lst=x) 
+21
source share

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

 msg = header + x 

by:

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

All Articles