Python imaplib: Cannot logout from imap - python

I wrote a python script to automate some tasks on my mail account. So, I can login to my yahoo mail account, read, delete (via imap) and send emails (via smtp). After that I want to logout. However, I am getting this error, which I do not know how to repair:
This is what happens:
Exception in close_imap
Traceback (most recent call last):
File "/Users/Tom/MeineDaten/Programmieren/Sportwetten/Tipico/Report-Gambling-Apps/emailing/Mailer.py", line 55, in close_imap
self.imap.close()
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/imaplib.py", line 445, in close
typ, dat = self._simple_command('CLOSE')
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/imaplib.py", line 1180, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/local/Cellar/python3/3.5.0/Frameworks/Python.framework/Versions/3.5/lib/python3.5/imaplib.py", line 928, in _command
', '.join(Commands[name])))
imaplib.IMAP4.error: command CLOSE illegal in state LOGOUT, only allowed in states SELECTED
And this is the corresponding code:
import imaplib
...other code here...
def close_imap(self):
if self.imap is None:
print("close_imap: self.imap is None. No further action taken. Returning.")
return
try:
self.imap.close()
self.imap.logout()
except Exception:
print("Exception in close_imap")
print(str(traceback.format_exc()))
pass
What am I doing wrong here?

You are trying to close a folder but you have not selected any.
This may be due to two thinks:
You never selected a folder in this session
You already closed the folder but you are trying to close it a second time.
You should only close a folder one time.
Note: This is not necessary in the IMAP protocol to close a folder before logging out.

Related

Exporting PPTx to PDF (issue using win32com or comtypes)

I'm having trouble executing part of a python (converting a PPTx to PDF, either with win32com or with comtypes):
obj = win32com.client.Dispatch('Powerpoint.Application')
obj.Visible = 1
doc = obj.Presentations.Open(file_name_ptx)
doc.SaveAs(file_name_pdf, FileFormat=32)
The python works perfectly if I run it from CMD, or even within sublime or equivalent. It also works if I run it through a window scheduled task.
However, it fails if it is run through another script, for example from another subprocessed python (either with POpen or with Run) or from php (using cmd_exe).
It also fails if that script is executed through a "remote" request (from another PC).
The failure always occurs in the same place, the script is not able to open the PPTx application:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 81, in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operacixf3n no disponible', None, None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "*******.PY", line 706, in
obj = win32com.client.Dispatch('Powerpoint.Application')
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 98, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 83, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147023584, 'Una sesixf3n de inicio especificada no existe. Es posible que haya finalizado.', None, None)
I have been looking for various solutions, I have tried with different modules, I have even tried to create a PowerShell file that converts PowerPoint to PDF and the exact same thing happens, if I run the PS1 from CMD it works perfectly, but if I run it remotely or through from another script, it fails for the exact same reason, it is unable to open an instance of PowerPoint.
I have also tried, remotely, to first activate the windows GUI (deactivate the user lock screen and access as if it were a real person) and then execute any script (PY, PS1, etc.), but still with the desktop properly open and without user lock screen the script fails at exactly the same point.
Would anyone know what the problem is and how to solve it?
Thank you.

Python - Get Instagram API Access Token

I am trying to call the Instagram Basic API to get the user info. However, I need to fetch the access token first for the authentication.
I have implemented the code for getting the same in python but I am only able to fetch the re-direct uri. Now, as a manual step we execute that uri on browser and get the code from the url.
But in case of programming how can I get the access token?
In below code: I am getting error
from instagram_basic_display.InstagramBasicDisplay import InstagramBasicDisplay
from flask import request
instagram_basic_display = InstagramBasicDisplay(app_id='5163403347035424', app_secret='80473de6ad506c837969e03b8ccdb4cb', redirect_url='https://mycogito.me/')
print(instagram_basic_display.get_login_url()) # Returns login URL you need to follow
code = request.args.get('code')
print(code)
Error
Traceback (most recent call last):
File "D:\Work Backup\Development\Workspaces\python\SocialMedia\src\com\social\media\HelloWorld.py", line 9, in <module>
https://api.instagram.com/oauth/authorize?client_id=5163403347035424&redirect_uri=https%3A%2F%2Fmycogito.me%2F&scope=user_profile%2Cuser_media&response_type=code
code = request.args.get('code')
File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object
return self.__local()
File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\globals.py", line 38, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
There is a package when you want to get data from instagram and written in python click.

Exscript TimeoutException

So I finally got exscript working properly (I think). I wanted to test it, so I setup a simple python script I believe should work:
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
account = read_login()
conn = SSH2()
conn.connect('router.domain.com')
conn.login(account)
conn.execute('terminal length 0')
conn.execute('show version')
print conn.response
conn.send('exit\r')
conn.close()
I run the script and I'm presented with the following:
kidd#server scripts$ python test1.py
Please enter your user name [kidd]:
Please enter your password:
It sits there for about 20 seconds, then I get this:
Traceback (most recent call last):
File "test1.py", line 7, in <module>
conn.login(account)
File "/usr/lib/python2.7/site-packages/Exscript/protocols/Protocol.py", line 597, in login
self.auto_app_authorize(app_account, flush = flush)
File "/usr/lib/python2.7/site-packages/Exscript/protocols/Protocol.py", line 846, in auto_app_authorize
self.get_driver().auto_authorize(self, account, flush, bailout)
File "/usr/lib/python2.7/site-packages/Exscript/protocols/drivers/one_os.py", line 43, in auto_authorize
conn.app_authorize(account, flush, bailout)
File "/usr/lib/python2.7/site-packages/Exscript/protocols/Protocol.py", line 820, in app_authorize
self._app_authenticate(account, password, flush, bailout)
File "/usr/lib/python2.7/site-packages/Exscript/protocols/Protocol.py", line 690, in _app_authenticate
raise TimeoutException(msg)
Exscript.protocols.Exception.TimeoutException: Buffer: '\rThis is a private system \r\n \r\nrouter>'
Am I missing something simple? Just trying to login to a router (as a normal user, non-privilege mode), run a show version, then log out. Any help would be appreciated. Thanks.
It looks like the banner you have configured is messing with the prompt that Exscript is expecting back from the device. I'd suggest either tweaking the protocol driver within Exscript to handle the prompt better, or making sure your banner is set up properly (or removing it all together)

Why does my code raise an exception?

Hi I am trying to create an FTP server and to aid the development I'm using pyftpdlib. What I wanted to do is to do some file operations if a user downloads a specific file but sometimes it raises an exception and I don't really know why.
I wrote my own handler in pyftpdlib after this tutorial: http://code.google.com/p/pyftpdlib/wiki/Tutorial#3.8_-_Event_callbacks
But something goes terribly wrong sometimes when the user downloads the log file (which I intend to do some file operations on) and I don't really understand why. I have another class which basically reads from a configuration file and the error message said it couldn't find FTP Section. But it's strange because I clearly have it in my configuration file and it is working sometimes perfectly.
May this error appear because I have two "Connection" objects? That's the only guess I have, so I would be very glad if someone could explain what's going wrong. Here is my code that's troubled (nevermind the file.name check because that was very recently added):
class ArchiveHandler(ftpserver.FTPHandler):
def on_login(self, username):
# do something when user login
pass
def on_logout(self, username):
# do something when user logs out
pass
def on_file_sent(self, file):
"What to do when retrieved the file the class is watching over"
attr = Connection()
if attr.getarchive() == 'true':
t = datetime.now()
if file.name == "log.log":
try:
shutil.copy2(file, attr.getdir() + ".archive/" + str(t.strftime("%Y-%m-%d_%H:%M:%S") + '.log'))
except OSError:
print 'Could not copy file'
raise
if attr.getremain() == 'false':
try:
os.remove(file)
except OSError:
print 'Could not remove file'
raise
The full source:
http://pastie.org/3552079
Source of the config-file:
http://pastie.org/3552085
EDIT-> (and of course the error):
[root]#85.230.122.159:40659 unhandled exception in instance <pyftpdlib.ftpserver.DTPHandler object at 0xb75f49ec>
Traceback (most recent call last):
File "/usr/lib/python2.6/asyncore.py", line 84, in write
obj.handle_write_event()
File "/usr/lib/python2.6/asyncore.py", line 435, in handle_write_event
self.handle_write()
File "/usr/lib/python2.6/asynchat.py", line 174, in handle_write
self.initiate_send()
File "/usr/lib/python2.6/asynchat.py", line 215, in initiate_send
self.handle_close()
File "/usr/local/lib/python2.6/dist-packages/pyftpdlib/ftpserver.py", line 1232, in handle_close
self.close()
File "/usr/local/lib/python2.6/dist-packages/pyftpdlib/ftpserver.py", line 1261, in close
self.cmd_channel.on_file_sent(filename)
File "ftp.py", line 87, in on_file_sent
File "ftp.py", line 12, in __init__
File "/usr/lib/python2.6/ConfigParser.py", line 311, in get
raise NoSectionError(section)
NoSectionError: No section: 'FTP Section'
The problem is in a section you didn't include. It says
File "ftp.py", line 12, in __init__
File "/usr/lib/python2.6/ConfigParser.py", line 311, in get
raise NoSectionError(section)
NoSectionError: No section: 'FTP Section'
So from the first line, we know that whatever is on line 12 of ftp.py is the problem (since everything below that isn't our code, so we assume that it's correct).
Line 12 is this:
self.ip = config.get('FTP Section', 'hostname')
And the error message says "No section: 'FTP Section'".
From this we can assume there's an error in the config file (that it doesn't have a "FTP Section").
Are you pointing at the correct config file? Is it in the same directory that you're running the script from? Being in the same folder as the script will not work, it must be the folder that you run the script from.
I think this is the problem you're having, since according to the documentation:
If none of the named files exist, the ConfigParser instance will contain an empty dataset.
You can confirm this by trying to open the file.
The problem in this case was that by reading the file it left the file open.
I changed to this and it's working much better:
config = ConfigParser.RawConfigParser()
fp = open('config.cfg')
config.readfp(fp)
And then when I'm finished reading in the constructor I add:
#Close the file
fp.close()
And voila, you can open how many objects of the class you want and it won't show any errors. :)

Creating a Draft message in Gmail using the imaplib in Python

I want to write a python module that sends data to a draft message in a G-mail account. I have written a script about two weeks ago that worked perfectly using imaplib. A simplified example of my module is below. (I have created a test email address for anyone to test this script on.)
import imaplib
import time
conn = imaplib.IMAP4_SSL('imap.gmail.com', port = 993)
conn.login('testpythoncreatedraft#gmail.com', '123456aaa')
conn.select('[Gmail]/Drafts')
conn.append("[Gmail]/Drafts", '', imaplib.Time2Internaldate(time.time()), "TEST")
It utilized the .append function, but today when I run the module and it produces the following error:
Traceback (most recent call last):
File "C:/Windows/System32/email_append_test.py", line 6, in <module>
conn.append("[Gmail]/Drafts", '', imaplib.Time2Internaldate(time.time()), "TEST")
File "C:\Python26\lib\imaplib.py", line 317, in append
return self._simple_command(name, mailbox, flags, date_time)
File "C:\Python26\lib\imaplib.py", line 1060, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "C:\Python26\lib\imaplib.py", line 895, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: APPEND command error: BAD ['Invalid Command']
As I said before, this module worked before. It successfully created draft messages with the string "Test" in its body. Since this script used to work, it seems more likely that it has something to do with a change Google made to the G-mail accounts IMAP features, but the error seems to indicate an error in the APPEND command. I have tested the python script on two different computer to see if my library file was corrupt, but the same error remained.
Also, I am using Python 2.6. Any help is appreciated.
Before the conn.append, add the following:
import email
Then change the conn.append line to read:
conn.append("[Gmail]/Drafts",
'',
imaplib.Time2Internaldate(time.time()),
str(email.message_from_string('TEST')))

Categories

Resources