0

I need to get a count of the emails received daily in a Gmail mailbox and save that count in a table. To do this I am using the imaplib:

import imaplib  
import re
obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)  
obj.login('xxx@gmail.com', 'password')  
obj.select('Inbox')     
('OK', ['50'])  
gmail_count = obj.search(None,'(SINCE "01-Sep-2020" BEFORE "02-Sep-2020")') 
print(gmail_count)

and I get something like this: ('OK', [b'28410 28411 28412 28413 28414 28415 28416 28417 28418 28419 28420 28421 28422 28423 28424 28425 28426 28427 28428 28429 28430 28431 28432 28433 28434 28435 28436 28437 28438 28439'])

I now need to count how many values are in this tuple to get the number of emails so I would like to replace the spaces with commas. How Can I do this?

Chris
  • 29,127
  • 3
  • 28
  • 51
  • 1
    `gmail_count[1][0].replace(" ", ",")`? – Chris Sep 02 '20 at 11:19
  • Thanks! not sure why I'm getting this error: TypeError: a bytes-like object is required, not 'str' – A Caradonna Sep 02 '20 at 11:25
  • It's because gmail_count[1][0] isn't a string but bytes, u can notice the 'b' character at the begining of the string; I edited my answer to show you how to convert the bytes array into string before the "replace" call – Xeyes Sep 02 '20 at 11:28
  • you're welcome. If my answer solved your problem can you please validate it to mark your issue as solved, thank. – Xeyes Sep 02 '20 at 11:45
  • I think you actually want to just call split(b’ ‘) to get a list, not replace it with commas. – Max Sep 04 '20 at 15:31

2 Answers2

0

You can use the replace built-in function to replace spaces by comas in a string

In your case you firstly have to convert your bytes array in a string with the decode("utf-8") function.

If your data are not utf-8 encoded you can change the parameter in the decode function with the correct encoding method.

values = gmail_count[1][0]
replaced = values.decode("utf-8").replace(" ", ",")
Xeyes
  • 583
  • 5
  • 25
0

You can also just use split to get a list, and then you can get the count and do any other list operations on it:

uidbytes = b’10 20 30’
uidlist = uidbytes.split(b’ ‘)
print(uidlist)
print(len(uidlist))

Output:

[b’10’, b’20, b’30’]
3

You can even change them to integers:

>>> [int(x) for x in uidlist]
[10, 20, 30]
Max
  • 10,701
  • 2
  • 24
  • 48