Message instance has no attribute 'read' in Google app engine mail receive - python

Code in receive handler
class LogSenderHandler(InboundMailHandler):
def receive(self, mail_message):
logging.info("Received a message from: " + mail_message.sender)
#logging.info("Received a message from: " + mail_message.attachments)
logging.info("Received a message from: " + mail_message.date)
logging.info("Received a message from: " + mail_message.subject)
report = DocFile()
report.doc_name = mail_message.subject
if mail_message.attachments is not None:
report.doc_file = mail_message.attachments
else:
report.doc_file = mail_message.bodies(content_type='text/plain')
report.put()
application = webapp.WSGIApplication([LogSenderHandler.mapping()], debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
code in url.py
inbound_services:
- mail
handlers:
- url: /_ah/mail/.+
script: handle_incoming_email.py
error when i try to send a simple email from http://localhost:8080/_ah/admin/inboundmail
Message send failure
Traceback (most recent call last):
File "F:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 509, in __call__
handler.post(*groups)
File "F:\Program Files\Google\google_appengine\google\appengine\ext\webapp\mail_handlers.py", line 58, in post
self.receive(mail.InboundEmailMessage(self.request.body))
File "F:\Program Files\Google\google_appengine\google\appengine\api\mail.py", line 547, in __init__
self.update_from_mime_message(mime_message)
File "F:\Program Files\Google\google_appengine\google\appengine\api\mail.py", line 1081, in update_from_mime_message
mime_message = _parse_mime_message(mime_message)
File "F:\Program Files\Google\google_appengine\google\appengine\api\mail.py", line 232, in _parse_mime_message
return email.message_from_file(mime_message)
File "F:\Python25\lib\email\__init__.py", line 66, in message_from_file
return Parser(*args, **kws).parse(fp)
File "F:\Python25\lib\email\parser.py", line 68, in parse
data = fp.read(8192)
AttributeError: Message instance has no attribute 'read'
EDIT
This error comes only on local machine and not on app engine

Do you have the latest version of the API? for the incoming mail function need to be the 1.2.6 or greatest.
Later i saw in google groups the "solution" I quote Joshua Smith
"I've found that you need to restart the local dev environment before
doing any inbound mail testing. Otherwise, you'll get that read error"
So every time that you change your code you MUST restart the server, even if only add white spaces (seriously)

Related

exchangelib connect to office 365 shared mailbox failed

I need to write a python script which checks for incoming e-mail in a shared mailbox hosted on office 365.
I have used python exchangelib 4.7.3:
Code
#!/usr/bin/env python3
import logging
from exchangelib import Credentials, Account, Configuration, DELEGATE
def list_mails():
credentials = Credentials('user#company.com', 'SecretPassword')
config = Configuration(server='outlook.office365.com', credentials=credentials)
account = Account(primary_smtp_address='sharedmailbox#company.com', config=config, autodiscover=False, access_type=DELEGATE)
for item in account.inbox.all().order_by('-datetime_received')[:100]:
print(item.subject, item.sender, item.datetime_received)
def main():
list_mails()
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
main()
Issue
Regardless of the different tries, the following error is showing up:
DEBUG:exchangelib.protocol:No retry: no fail-fast policy
DEBUG:exchangelib.protocol:Server outlook.office365.com: Retiring session 87355
DEBUG:exchangelib.protocol:Server outlook.office365.com: Created session 82489
DEBUG:exchangelib.protocol:Server outlook.office365.com: Releasing session 82489
Traceback (most recent call last):
File "/Users/test/Code/./orderalert.py", line 24, in <module>
main()
File "/Users/test/Code/./orderalert.py", line 20, in main
list_mails()
File "/Userstest/Code/./orderalert.py", line 11, in list_mails
account = Account(primary_smtp_address='sharedmailbox#company.com', config=config, autodiscover=False, access_type=DELEGATE)
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/account.py", line 204, in __init__
self.version = self.protocol.version.copy()
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/protocol.py", line 483, in version
self.config.version = Version.guess(self, api_version_hint=self._api_version_hint)
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/version.py", line 233, in guess
list(ResolveNames(protocol=protocol).call(unresolved_entries=[name]))
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/services/common.py", line 187, in _elems_to_objs
for elem in elems:
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/services/common.py", line 245, in _chunked_get_elements
yield from self._get_elements(payload=payload_func(chunk, **kwargs))
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/services/common.py", line 265, in _get_elements
yield from self._response_generator(payload=payload)
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/services/common.py", line 227, in _response_generator
response = self._get_response_xml(payload=payload)
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/services/common.py", line 343, in _get_response_xml
r = self._get_response(payload=payload, api_version=api_version)
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/services/common.py", line 297, in _get_response
r, session = post_ratelimited(
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/util.py", line 917, in post_ratelimited
protocol.retry_policy.raise_response_errors(r) # Always raises an exception
File "/opt/homebrew/lib/python3.9/site-packages/exchangelib/protocol.py", line 688, in raise_response_errors
raise UnauthorizedError(f"Invalid credentials for {response.url}")
exchangelib.errors.UnauthorizedError: Invalid credentials for https://outlook.office365.com/EWS/Exchange.asmx
DEBUG:exchangelib.protocol:Server outlook.office365.com: Closing sessions
Tried solutions (no luck with them)
The user#company.com credentials are valid, I can log myself in the web interface (no MFA or other enforced)
I have tried the auto discovery:
account = Account('sharedmailbox#company.com', credentials=credentials, autodiscover=True, access_type=DELEGATE)
Disable TLS Validation when connecting
As suggested added a "on" subdomain on on.company.com for the emails addresses.
Tested the overall setup for autodiscovery on testconnectivity.microsoft.com
On the Office 365 Azure AD admin web interface, I can see a successful login performed by the script.

Flask object has no attribute app_context

I'm trying to send emails periodically with flask mail, but I'm stuck with this error: Flask object has no attribute app_context
def mail_periodic():
print "sending mail at " +time.ctime()
app = current_app._get_current_object()
msg = Message("no-reply: Avantgarde.Rentals",
sender="avantgarde.rentals.noreply#gmail.com",
)
msg.add_recipient('aladinne.k#gmail.com')
msg.body = 'Email periodic '
mail2 = Mail(app)
with app.app_context():
mail2.send(msg)
print"email sent "
threading.Timer(5, mail_periodic).start()
#app.route('/startcronemailing')
def startcronemailing():
try:
mail_periodic()
except Exception, exception:
return exception.message
return "crone mailing started"
the exception that i got :
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 1073, in run
self.function(*self.args, **self.kwargs)
File "app.py", line 113, in mail_periodic
host_link='http://' + request.host,
File "C:\Python27\lib\site-packages\werkzeug\local.py", line 336, in __getattr__
return getattr(self._get_current_object(), name)
File "C:\Python27\lib\site-packages\werkzeug\local.py", line 295, in _get_current_object
return self.__local()
File "C:\Python27\lib\site-packages\flask\globals.py", line 19, in _lookup_object
raise RuntimeError('working outside of request context')
RuntimeError: working outside of request context
please note that even if i use another mailing service like sendgrid i got the same error
You have to pass app instance as args. If you use current_app._get_current_object() to get app instance inside target function, you will not get the right app in another thread. For example:
from threading import Thread
from flask import current_app
from flask_mail import Message
from bluelog.extensions import mail
def _send_async_mail(app, message): # target function
with app.app_context():
mail.send(message)
def send_async_mail(subject, to, html):
app = current_app._get_current_object() # get the real app instance
message = Message(subject, recipients=[to], html=html)
thr = Thread(target=_send_async_mail, args=[app, message]) # pass app
thr.start()
return thr

Python cherrypy and bottle with ssl - server fails to save a file bigger than 102199 bytes

The next problem happens only when SSL is enabled!
I am running a server with bottle version 0.12.6 and cherrypy version 3.2.2 using https.
The client code sends a file to the server and the server saves it.
when i send a file with size below 102199 bytes, it is received and saved successfully. However, When i send a file with size bigger or equal to 102199, I get the exception:
The Server Code:
from bottle import request, response,static_file, run,server_names
from OpenSSL import crypto,SSL
from bottle import Bottle, run, request, server_names, ServerAdapter
app = Bottle()
app.mount('/test' , app)
class MySSLCherryPy(ServerAdapter):
def run(self, handler):
from cherrypy import wsgiserver
server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler)
server.ssl_certificate = "./cert"
server.ssl_private_key = "./key"
try:
server.start()
finally:
server.stop()
#app.post('/upload')
def received_file():
file = request.files.file
# file.save("./newfile")
file_path="./newfile"
with open(file_path, 'w') as open_file:
open_file.write(file.read())
if __name__=='__main__':
server_names['mysslcherrypy'] = MySSLCherryPy
run(app, host='0.0.0.0', port=4430, server='mysslcherrypy')
exit(0)
Why does the server fail to get file more than a given limit? is there a limit that i need to change?
(I tried to set the constant MEMFILE_MAX at the function received_file but it didn't help)
The problem vanish if the server is http and not https!
The exception in plain text (in case you cannot view the image):
Traceback (most recent call last):
File "/usr/lib/python2.6/site-packages/bottle.py", line 861, in _handle
return route.call(**args)
File "/usr/lib/python2.6/site-packages/bottle.py", line 1727, in wrapper
rv = callback(*a, **ka)
File "testser", line 28, in received_file
file = request.files.file
File "/usr/lib/python2.6/site-packages/bottle.py", line 165, in get
if key not in storage: storage[key] = self.getter(obj)
File "/usr/lib/python2.6/site-packages/bottle.py", line 1106, in files
for name, item in self.POST.allitems():
File "/usr/lib/python2.6/site-packages/bottle.py", line 165, in get
if key not in storage: storage[key] = self.getter(obj)
File "/usr/lib/python2.6/site-packages/bottle.py", line 1222, in POST
args = dict(fp=self.body, environ=safe_env, keep_blank_values=True)
File "/usr/lib/python2.6/site-packages/bottle.py", line 1193, in body
self._body.seek(0)
File "/usr/lib/python2.6/site-packages/bottle.py", line 165, in get
if key not in storage: storage[key] = self.getter(obj)
File "/usr/lib/python2.6/site-packages/bottle.py", line 1162, in _body
for part in body_iter(read_func, self.MEMFILE_MAX):
File "/usr/lib/python2.6/site-packages/bottle.py", line 1125, in _iter_body
part = read(min(maxread, bufsize))
File "/usr/lib/python2.6/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 329, in read
data = self.rfile.read(size)
File "/usr/lib/python2.6/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 1052, in read
assert n <= left, "recv(%d) returned %d bytes" % (left, n)
AssertionError: recv(47) returned 48 bytes
Solution
In the file bottle.py I changed the value of .MEMFILE_MAX to be 10000000 and by this i solved the problem. The best way to do this is from your server code by adding the next line:
bottle.BaseRequest.MEMFILE_MAX=30000000000

500 Internal Server Error trying to start session with shopify python api

I'm following the tutorial on https://github.com/Shopify/shopify_python_api but at step 4 I always get an "500 Internal Server Error".
I'm not sure whether I do follow the steps correctly.
After step 3 I visit the URL in permission_url in my browser click "Install" and then copy the data from the URL I get redirected to into a python dict called params.
On executing step 4 I get:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File ".../lib/python2.7/site-packages/shopify/session.py", line 53, in __init__
self.token = self.request_token(params['code'])
File ".../lib/python2.7/site-packages/shopify/session.py", line 90, in request_token
response = connection.post(access_token_path, ShopifyResource.headers)
File ".../lib/python2.7/site-packages/pyactiveresource/connection.py", line 313, in post
return self._open('POST', path, headers=headers, data=data)
File ".../lib/python2.7/site-packages/shopify/base.py", line 18, in _open
self.response = super(ShopifyConnection, self)._open(*args, **kwargs)
File ".../lib/python2.7/site-packages/pyactiveresource/connection.py", line 258, in _open
response = Response.from_httpresponse(self._handle_error(err))
File ".../lib/python2.7/site-packages/pyactiveresource/connection.py", line 367, in _handle_error
raise ServerError(err)
ServerError: HTTP Error 500: Internal Server Error
For a private application you do not need to go through the authorization steps to get a token. The token is simply private applications password. So activating a session just requires doing:
session = shopify.Session(SHOP_URL)
session.token = PRIVATE_APPLICATION_PASSWORD
shopify.ShopifyResource.activate_session(session)

Python soap using soaplib (server) and suds (client)

This question is related to:
Python SOAP server / client
In the case of soap with python, there are recommendation to use soaplib (http://wiki.github.com/jkp/soaplib) as soap server and suds (https://fedorahosted.org/suds/) as soap client.
My target is to create soap services in python that can be consumed by several clients (java, etc).
I tried the HelloWorld example from soaplib (http://trac.optio.webfactional.com/wiki/HelloWorld).
It works well when the client is also using soaplib.
Then, I tried to use suds as client consuming the HelloWorld services and it fail.
-Why this is happening? Does soaplib server has problems to consumed by different clients?
Here the code for the server:
from soaplib.wsgi_soap import SimpleWSGISoapApp
from soaplib.service import soapmethod
from soaplib.serializers.primitive import String, Integer, Arraycode
class HelloWorldService(SimpleWSGISoapApp):
#soapmethod(String,Integer,_returns=Array(String))
def say_hello(self,name,times):
results = []
for i in range(0,times):
results.append('Hello, %s'%name)
return results
if __name__=='__main__':
from cherrypy.wsgiserver import CherryPyWSGIServer
#from cherrypy._cpwsgiserver import CherryPyWSGIServer
# this example uses CherryPy2.2, use cherrypy.wsgiserver.CherryPyWSGIServer for CherryPy 3.0
server = CherryPyWSGIServer(('localhost',7789),HelloWorldService())
server.start()
This is the soaplib client:
from soaplib.client import make_service_client
from SoapServerTest_1 import HelloWorldService
client = make_service_client('http://localhost:7789/',HelloWorldService())
print client.say_hello("Dave",5)
Results:
>>> ['Hello, Dave', 'Hello, Dave', 'Hello, Dave', 'Hello, Dave', 'Hello, Dave']
This is the suds client:
from suds.client import Client
url = 'http://localhost:7789/HelloWordService?wsdl'
client1 = Client(url)
client1.service.say_hello("Dave",5)
Results:
>>> Unhandled exception while debugging...
Traceback (most recent call last):
File "C:\Python25\Lib\site-packages\RTEP\Sequencing\SoapClientTest_1.py", line 10, in <module>
client1.service.say_hello("Dave",5)
File "c:\python25\lib\site-packages\suds\client.py", line 537, in __call__
return client.invoke(args, kwargs)
File "c:\python25\lib\site-packages\suds\client.py", line 597, in invoke
result = self.send(msg)
File "c:\python25\lib\site-packages\suds\client.py", line 626, in send
result = self.succeeded(binding, reply.message)
File "c:\python25\lib\site-packages\suds\client.py", line 658, in succeeded
r, p = binding.get_reply(self.method, reply)
File "c:\python25\lib\site-packages\suds\bindings\binding.py", line 158, in get_reply
result = unmarshaller.process(nodes[0], resolved)
File "c:\python25\lib\site-packages\suds\umx\typed.py", line 66, in process
return Core.process(self, content)
File "c:\python25\lib\site-packages\suds\umx\core.py", line 48, in process
return self.append(content)
File "c:\python25\lib\site-packages\suds\umx\core.py", line 63, in append
self.append_children(content)
File "c:\python25\lib\site-packages\suds\umx\core.py", line 140, in append_children
cval = self.append(cont)
File "c:\python25\lib\site-packages\suds\umx\core.py", line 61, in append
self.start(content)
File "c:\python25\lib\site-packages\suds\umx\typed.py", line 77, in start
found = self.resolver.find(content.node)
File "c:\python25\lib\site-packages\suds\resolver.py", line 341, in find
frame = Frame(result, resolved=known, ancestry=ancestry)
File "c:\python25\lib\site-packages\suds\resolver.py", line 473, in __init__
resolved = type.resolve()
File "c:\python25\lib\site-packages\suds\xsd\sxbasic.py", line 63, in resolve
raise TypeNotFound(qref)
TypeNotFound: Type not found: '(string, HelloWorldService.HelloWorldService, )'
try to import primitives into your class:
class HelloWorldService(SimpleWSGISoapApp):
from soaplib.serializers.primitive import String, Integer, Arraycode
#soapmethod(String,Integer,_returns=Array(String))
this bug is fixed if you get the latest sources from the trunk, see https://github.com/soaplib/soaplib/pull/12 for details

Categories

Resources