I apologise in advance, I know this will be a simple answer but I'm not having any luck and it's starting to bug me.
I just want to log into my Gmail account using imaplib and credentials pulled from a file.
I can log into Gmail no worries using:
srv = imaplib.IMAP_SSL("imap.gmail.com")
srv.login("bob#gmail.com", "mypassword")
But instead I'm trying to use a text file (credentials.dat). Inside the file is 2 lines:
bob#gmail.com
mypassword
My code is as follows:
import imaplib
CREDS = open("credentials.dat", "r")
account = CREDS.readline()
password = CREDS.readline()
srv = imaplib.IMAP4_SSL("imap.gmail.com")
srv.login(account, password)
When I run it I get the followign error:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib64/python2.4/imaplib.py", line 480, in login
typ, dat = self._simple_command('LOGIN', user, self._quote(password))
File "/usr/lib64/python2.4/imaplib.py", line 1028, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/lib64/python2.4/imaplib.py", line 865, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: LOGIN command error: BAD ['Failed to parse your command r13if7033890ebd.47']
I assume it doesn't like the data type being entered into srv.login, but I have no idea how else to do it.
There are so many more things I want to do once I get into Gmail (read emails, post, etc), but it's looking like an uphill battle if I can't even log in :(
Thanks for your time.
readline() includes the newline character at the end of the line, so you're really saying: login with 'bob#gmail.com\n'
Try readline().strip() to strip whitespace characters from both sides of the line.
Related
I've build a very simple script that fetches emails from an Outlook inbox. It looks like this:
from imap_tools import MailBox
inbox = MailBox("outlook.office365.com").login("email", "password")
for email in inbox.fetch(): # bulk=True
print(email)
It's working when I use it like this. Though, when passing the arg bulk=True on the fetch() function it will raise the following error:
Traceback (most recent call last):
File "/Users/julius/Library/Application Support/JetBrains/IntelliJIdea2022.3/scratches/scratch_1.py", line 5, in <module>
for email in inbox.fetch(bulk=True):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/imap_tools/mailbox.py", line 171, in fetch
for fetch_item in (self._fetch_in_bulk if bulk else self._fetch_by_one)(nums, message_parts, reverse): # noqa
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/imap_tools/mailbox.py", line 144, in _fetch_in_bulk
fetch_result = self.client.fetch(','.join(message_nums), message_parts)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/imaplib.py", line 548, in fetch
typ, dat = self._simple_command(name, message_set, message_parts)
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/imaplib.py", line 1230, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/imaplib.py", line 1008, in _command
raise self.abort('socket error: %s' % val)
imaplib.IMAP4.abort: socket error: EOF occurred in violation of protocol (_ssl.c:2396)
Has anyone got a clue on how to fix this?
Right answer: combine bulk and limit args.
Text from docs:
For actions with a large number of messages imap command may be too large and will cause exception at server side, use 'limit' argument for fetch in this case.
I'm trying to select a specific mail in my imap folder without having a clear identifier. The only thing I have is a plaintext copy of the mail saved as an eml file.
I tried to load the mail from the file using the email module but I keep getting errors whenever I run the search function of the imaplib module starting from the data contained in the mail.
In this instance I'm assuming that the mail comes from the current mailbox.
This is the code I'm using now
import imaplib, email
m = imaplib.IMAP4_SSL(IMAP_SERVER)
m.login(IMAP_USER, IMAP_PWD)
m.select()
mail_file = open('./file.eml')
raw_mail = mail_file.read()
mail = email.message_from_string(raw_mail)
resp, items = m.search(None, '(FROM "' + mail["FROM"] +'")')
But I'm getting the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\user\AppData\Local\conda\conda\envs\py353\lib\imaplib.py", line 707, in search
typ, dat = self._simple_command(name, *criteria)
File "C:\Users\user\AppData\Local\conda\conda\envs\py353\lib\imaplib.py", line 1180, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "C:\Users\user\AppData\Local\conda\conda\envs\py353\lib\imaplib.py", line 1011, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: SEARCH command error: BAD [b'Error in IMAP command SEARCH: Unknown argument DATE (0.000 + 0.000 secs).']`
How should I do this and what filters can I use to have a reasonable chance of getting exactly the mail I want in the results?
Edit: as requested my mail['FROM'] returns 'test sender\n\t<sender#domain.com>'
I made a test hardcoding a similar format and removing the special characters but of course I'm returned a different mail with matched sender.
Also I'm trying to get to the correct mail without altering any data in the most automatic way possible.
I would like to sort the emails by arrival time.
Here is the code:
data = get_credential('info.txt')
imap_conn = create_connection(data, 'outlook.office365.com')
imap_conn.select('INBOX', readonly=False)
result, messages = imap_conn.sort('ARRIVAL', 'UTF-8', 'FROM peter#gmail.com SINCE "'+(datetime.date.today()-datetime.timedelta(4)).strftime('%d-%b-%Y')+'"
It returns the following error:
File "C:\Program Files\Python37\lib\imaplib.py", line 794, in sort
typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria)
File "C:\Program Files\Python37\lib\imaplib.py", line 1196, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "C:\Program Files\Python37\lib\imaplib.py", line 1027, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.IMAP4.error: SORT command error: BAD [b'Command Error. 12']
How to solve the problem?
Is the input charset UTF-8 correct? How to get it from messages?
Office365 doesn't support the SORT extension.
* CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CLIENTACCESSRULES CLIENTNETWORKPRESENCELOCATION BACKENDAUTHENTICATE CHILDREN IDLE NAMESPACE LITERAL+
You should check CAPABILITY before using any extensions.
I'm trying to get my account information by evernote api on python, however, I got errors :
Traceback (most recent call last): File "", line 1, in
File "build/bdist.linux-x86_64/egg/evernote/api/client.py", line 148, in delegate_method
File "build/bdist.linux-x86_64/egg/evernote/edam/userstore/UserStore.py", line 1033, in getUser
File "build/bdist.linux-x86_64/egg/evernote/edam/userstore/UserStore.py", line 1058, in recv_getUser
evernote.edam.error.ttypes.EDAMSystemException: EDAMSystemException(errorCode=8, rateLimitDuration=None, _message='authenticationToken')
My python code as below:
from evernote.api.client import EvernoteClient
dev_token="my develop token"
client = EvernoteClient(token=dev_token)
userStore = client.get_user_store()
user = userStore.getUser()
I'm sure I've generated a valid developer token for my Evernote account, as shown in the picture, I have a develop token in my account link
Is there anything I missed?
By the way, I use the code above and replace the key with another develop token generated by Evernote sandbox account, it's ok.
If you are not on sandbox, try:
client = EvernoteClient(token=dev_token, sandbox=False)
I'm trying to do a search using imaplib with variables. When I hard code the information the search works great.
result, data = mail.search(None,'(SENTSINCE "15-Oct-2015" SENTBEFORE "19-Oct-2015")'.format(date=date))
I've tried lots of ways to setup variables and from other posts it seems the best way is setup the entire search parameters as the variable and call it that way.
search_string = '(SENTSINCE \"' + start_date_format + '\" SENTBEFORE \"' + format_endday + '\" )\'.format(date=date)'
result, data = mail.search(None, search_string)
The print of the variable setup looks accurate:
(SENTSINCE "12-Oct-2015" SENTBEFORE "19-Oct-2015" )'.format(date=date)
I'm getting the following error:
Traceback (most recent call last):
File "infringment-report.py", line 74, in <module>
result, data = mail.search(None, search_string)
File "/usr/lib/python2.7/imaplib.py", line 639, in search
typ, dat = self._simple_command(name, *criteria)
File "/usr/lib/python2.7/imaplib.py", line 1087, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/lib/python2.7/imaplib.py", line 917, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: SEARCH command error: BAD ['The specified message set is invalid.']
I've been banging my head on this for a while, an help is appreciated.
I am also a newbie in python and imaplib but i guess this will work just fine.
For retrieving mails having name stored in a variable say fromname
then
let criteria = ['From', fromname]
typ, [msg_id] = mail.search(None, *criteria).