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()
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With