title: find last 7 days mail from gmail to csv in python
body: <p>Facing issue while extracting last 7 days email from gmail to csv by using IMAP in python. Below is the code i have built using help from blogs.</p>
  
  <pre><code># -*- coding: utf-8 -*-
  """
  Created on Wed Dec  6 18:34:56 2017
  
  @author: ravi
  """
  
  import email, getpass, imaplib, os , datetime , csv
  
  detach_dir = '.' # directory where to save attachments (default: current)
  user = input("Enter your GMail username:")
  pwd = getpass.getpass("Enter your password: ")
  
  # connecting to the gmail imap server
  m = imaplib.IMAP4_SSL("imap.gmail.com")
  m.login(user,pwd)
  m.select("inbox") # here you a can choose a mail box like INBOX instead
  m.list()# to get all the mailboxes
  
  
  
  date = (datetime.date.today() - datetime.timedelta(7)).strftime("%d-%b-%Y")
  result, data = m.search(None, '(SENTSINCE {date})'.format(date=date))
  ids = data[0]
  id_list = ids.split()
  
  final_list = [ ]
  
  
  for emailid in id_list:
      temp_dict = { }
      result, data = m.fetch(id_list, "(RFC822)")# fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
      email_body = data[0][1] # getting the mail content
      mail = email.message_from_bytes(email_body) # parsing the mail content to get a mail object
      temp_dict['Sender'] = mail["From"]
      temp_dict['Subject'] = mail["Subject"]
      temp_dict['Date'] = mail["Date"]
  
      print ("["+mail["From"]+"] :" + mail["Subject"] +mail["Date"])
  
      print (temp_dict)
      final_list.append(temp_dict)
  
  #exporting the values as .csv
  with open('CSV_NAME.csv', 'w', encoding='utf-8', newline = '') as csvfile: 
      fieldnames = ['Sender','Subject','Date']
      writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter = ',')
      writer.writeheader()
      for val in final_list:
          writer.writerow(val)
  </code></pre>
  
  <p>In this code the data is of the type list which is not accepting the type byte. How to resolve this ?</p>
  
  <p>UPDATE1:-</p>
  
  <p>Tried a new piece of code. Understood what the problem is anyway to solve it?</p>
  
  <pre><code># -*- coding: utf-8 -*-
  """
  Created on Tue Dec  5 19:36:33 2017
  
  @author: ravi
  """
  
  
  import email, getpass, imaplib, os , datetime , csv
  
  detach_dir = '.' # directory where to save attachments (default: current)
  user = input("Enter your GMail username:")
  pwd = getpass.getpass("Enter your password: ")
  
  # connecting to the gmail imap server
  m = imaplib.IMAP4_SSL("imap.gmail.com")
  m.login(user,pwd)
  m.select("inbox") # here you a can choose a mail box like INBOX instead
  m.list()# to get all the mailboxes
  
  
  
  date = (datetime.date.today() - datetime.timedelta(7)).strftime("%d-%b-%Y")
  resp, items = m.uid('search', None, '(SENTSINCE {date})'.format(date=date)) # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
  items = items[0].split() # getting the mails id
  
  final_list = [ ]
  
  for emailid in items:
      temp_dict = { }
      resp, data = m.uid('fetch',items,'(RFC822)')# fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
      email_body = data[0][1] # getting the mail content
      mail = email.message_from_bytes(email_body) # parsing the mail content to get a mail object
      temp_dict['Sender'] = mail["From"]
      temp_dict['Subject'] = mail["Subject"]
      temp_dict['Date'] = mail["Date"]
  
      print ("["+mail["From"]+"] :" + mail["Subject"] +mail["Date"])
  
      print (temp_dict)
      final_list.append(temp_dict)
  
  
  
  
  
  #exporting the values as .csv
  with open('CSV_NAME.csv', 'w', encoding='utf-8', newline = '') as csvfile: 
      fieldnames = ['Sender','Subject','Date']
      writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter = ',')
      writer.writeheader()
      for val in final_list:
          writer.writerow(val)
  </code></pre>
  
  <p>I get the error:-</p>
  
  <pre><code>---&gt; 31     resp, data = m.uid('fetch',items,'(RFC822)')# fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
  
  \Anaconda3\lib\imaplib.py in _command(self, name, *args)
      943             if isinstance(arg, str):
      944                 arg = bytes(arg, self._encoding)
  --&gt; 945             data = data + b' ' + arg
      946 
      947         literal = self.literal
  TypeError: can't concat bytes to list
  </code></pre>
  
  <p>Anyway to solve it</p>