Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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()
like image 617
Enzo Vidal Avatar asked Oct 23 '14 05:10

Enzo Vidal


People also ask

How do you concatenate a string and a list object in Python?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.

Why can't Python concatenate str and int objects?

In Python, we cannot concatenate a string and an integer together. They have a different base and memory space as they are completely different data structures.

Why can't I concatenate in Python?

Python does not support the auto type of the variable to be cast. You can not concatenate an integer value to a string. The root cause of this issue is due to the concatenation between an integer value and a string object. Before concatenation, an integer value should be converted to a string object.

Can only concatenate str not list to STR?

The Python "TypeError: can only concatenate str (not "list") to str" occurs when we try to concatenate a string and a list. To solve the error, access the list at a specific index to concatenate two strings, or use the append() method to add an item to the list.


1 Answers

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)
like image 152
David Sanders Avatar answered Oct 04 '22 01:10

David Sanders