I am trying to print pieces of an email (from, subject, body) with Python 3.5. I get a weird index error:
Traceback (most recent call last):
File "/home/user/PycharmProjects/email/imaplib_fetch_rfc822.py", line 21, in <module>
subject_, from_, to_, body_, = ' ' + email[0], email[1], email[2], 'Body: ' + email[4]
IndexError: list index out of range
I am not sure what is causing this, though I suspect that my tangle of fors and splits is the culprit. I am a noobie coder, so I imagine what I'm doing is far from elegant:
import imaplib
import imaplib_connect
with imaplib_connect.open_connection() as c:
c.select('INBOX')
typ, [msg_ids] = c.search(None, 'TEXT', 'Sunday')
for num in msg_ids.split():
typ, msg_data = c.fetch(num, '(RFC822)')
for raw_email in msg_data:
# raw_email is a tuple of len==2, we need the 2nd item:
b = raw_email[1]
email = str(b).split('\r\n')
subject_, from_, to_, body_, = ' ' + email[0], email[1], email[2], 'Body: ' + email[4]
print(subject_, '\n',
from_, '\n',
body_, '\n')
I don't understand what's the problem. One thing to note is that for the email parts email[0], email[1], email[2], and email[4], is that I skipped email[3] because it prints some random email meta data junk. Can anyone see what I'm doing wrong? And what can I do to remedy the error?