Creating a Draft message in Gmail using the imaplib in Python - 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')))

Related

api key reading config file - binance trading bot python: SyntaxError: (unicode error)

I've just started today to code! so please be kind! :D
After a long we to install programs and libraries in coding my fist "trading bot"
I'm trying to connect to my test-api in Binance but I have an issue.
Here my lines of coding
Here my error that i cant fix [syntax error][2]
Ive already done:
uninstall and install again pip python-binance
install conda twisted
install pip update same packages
Any suggestions?
Many thanks
--- edit
photo of errors
ive tried all 3 types of suggestion
now pythons tell me there there is no module named 'binance' how is possible?
- relevant code
# Importing libraries
from binance.client import Client
import configparser
# Loading keys from config file
config = configparser.ConfigParser()
config.read_file(open('<C:\\Users\\ssida\\OneDrive\\Documenti\\GitHub\\AI7XF205SS\\secret.cfg>'))
test_api_key = config.get('BINANCE', 'TEST_API_KEY')
test_secret_key = config.get('BINANCE', 'TEST_SECRET_KEY')
client = Client(test_api_key, test_secret_key)
client.API_URL = 'https://testnet.binance.vision/api' # To change endpoint URL for test account
info = client.get_account() # Getting account info
print(info)
edit 2x ---
i think che path now works, but now i have a new issue... PI Error (code+-2014).. gonna search what is that..
seems that API key format is invalid :(
[Running] python -u "c:\Users\ssida\OneDrive\Documenti\GitHub\AI7XF205SS\getting_account_info.py"
Traceback (most recent call last):
File "c:\Users\ssida\OneDrive\Documenti\GitHub\AI7XF205SS\getting_account_info.py", line 15, in <module>
info = client.get_account() # Getting account info
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 1822, in get_account
return self._get('account', True, data=params)
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 292, in _get
return self._request_api('get', path, signed, version, **kwargs)
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 242, in _request_api
return self._request(method, uri, signed, **kwargs)
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 237, in _request
return self._handle_response()
File "C:\Users\ssida\anaconda3\lib\site-packages\binance\client.py", line 285, in _handle_response
raise BinanceAPIException(self.response)
binance.exceptions.BinanceAPIException: APIError(code=-2014): API-key format invalid.
[Done] exited with code=1 in 1.944 seconds
The problem is the backslash is a special character (ex \n marks a new line)
You can fix this by either adding r before the path
r'C:\Users\...'
or change the backslash with double ones
'C:\\Users\\...'
or replace with '/'
'C:/Users/...'
EDIT
Remove the '<>' from the start and end of the path because open takes it as it is

Python imaplib: Cannot logout from imap

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.

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)

imaplib.select on big inbox: Too many arguments for command

I am trying to access to my emails in Gmail from a python script. The code I use is the following:
import imaplib
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login("username","password")
m.select("[Gmail]/All Mail")
When running this code in python 2, it works fine, I get the list of all my emails. In python 3 hoverer it fails with the error
>>> m.select("[Gmail]/All Mail")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.2/imaplib.py", line 674, in select
typ, dat = self._simple_command(name, mailbox)
File "/usr/lib/python3.2/imaplib.py", line 1121, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/lib/python3.2/imaplib.py", line 957, in _command_complete
raise self.error('%s command error: %s %s' % (name, typ, data))
imaplib.error: SELECT command error: BAD [b'[CLIENTBUG] Too many arguments for command']
I have done a bit of testing. It works fine on other folder such as "Inbox" where I get only 400 emails (vs 6000 in "All Mail").
Is it a problem related to the size of the list ? Why is it different in python 2 and 3 ?
Thank you
Try using m.select('"[Gmail]/All Mail"'), so that the double quotes get transmitted.
I suspect imaplib is not properly quoting the string, so the server gets what looks like two arguments: [Gmail]/All and Mail.

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. :)

Categories

Resources