Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I get IndexError: string index out of range in this code?

message_text = ["text1\n", variable1, "\ntext2", variable2, "\ntext3", variable3]
u = MIMEText(message_text[0][1][2][3][4][5])
u['Subject'] = 'title of email'
s.sendmail("test1@test.com", "example1@example.com", u.as_string())

I got the error on this line:

u = MIMEText(message_text[0][1][2][3][4][5])

The error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

IndexError: string index out of range

What should I do?

When creating u, I loaded the indices 0, 1, 2, 3, 4, 5 from message_text, but that created the error.

Example Error Screen

>Solution :

It looks like you are using a multi-dimensional array.
Here’s what python sees.

Take message_text[0] which is "text1\n"

Now take message_text[0][1] which is "e"

Now with message_text[0][1][2] we try to find what is the third element in "e"
This doesn’t make sense, because the string "e" only has one element: the character 'e'.

If you want to add them all together, you’ll need to convert your variables into text, and string them together.

u = MIMEText(message_text[0] + str(message_text[1]), message_text[2], str(message_text[3]), message_text[4], str(message_text[5]))

Converts all your variables into one long string before passing it the MIMEText command.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading