Google app engine send mail raises ApplicationError: 1 Internal Error - python

Years back I built a simple mail form that has been working like a champ, but in the last couple months the logs show I'm getting an error when EmailMessage's send() method gets called.
I wrote a quick test to see if a stripped down version of an EmailMessage would work without error:
class TestEmail(webapp.RequestHandler):
def get(self):
fromAddress = "APPOWNEREMAIL#gmail.com"
email = mail.EmailMessage(sender=fromAddress)
email.to = self.request.get('to') + '#gmail.com'
email.subject = "Test Email"
email.body = "Testing the email system"
email.html = "<strong>Testing the <em>email</em> system</strong>"
email.check_initialized()
email.send()
Simple enough, but if I call that with:
http://MYAPPNAME.appspot.com/test-email?to=TOTALLYLEGITEMAIL
I still get the same error (note check_initialized() isn't throwing an error):
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/_webapp25.py", line 701, in __call__
handler.get(*groups)
File "/base/data/home/apps/s~myappname/3.354527616249361817/myappname.py", line 370, in get
email.send()
File "/base/python_runtime/python_lib/versions/1/google/appengine/api/mail.py", line 895, in send
raise e
ApplicationError: ApplicationError: 1 Internal error
I haven't made any recent changes to the app, it's a lightly used app well below quota, it's sending as the email associated with the app owner and after spending a few hours scrutinizing the code, I'm still no closer to an answer.
Even more distressing, every Google search I come up with offers no new help. The best I could find was this question: Google app engine send mail service raises exception which sounds exactly like my problem, but in that case there wasn't a solution, the problem just went away.
Any idea how I can track this one down? Let me know if I need to clarify anything. Thanks!

What is your appid?
There is currently an issue that sending mail from an application whose appid is the same as the owner's gmail name will fail. eg, I have a gmail address "moishel at gmail dot com"; if I created an app whose appid is 'moishel' (before version 1.6.0) it will fail when trying to send mail. Note that this problem does not exist for apps created with version 1.6.0 or after.
Here's the issue: http://code.google.com/p/googleappengine/issues/detail?id=5320

Related

Print email's body on Outlook with Python

I've been trying to print the email's body from the emails that I receive in Outlook for a while, but I'm having the following error:
Traceback (most recent call last):
File "c:\Users\RMBORGE\Desktop\PythonLib\tempCodeRunnerFile.python", line 10, in <module>
print(message.body)
File "C:\Users\RMBORGE\AppData\Roaming\Python\Python39\site-packages\win32com\client\dynamic.py", line 543, in __getattr__
ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147467259, 'Unspecified error', None, None)
Could someone help me?
Please see my code below:
from email import message
import email
import win32com.client as client
outlook = client.Dispatch('Outlook.Application').GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message = messages.GetLast()
print(message.body)
Please remember that Outlook folders may contain different kind of items - mails, documents, notes and etc. Before accessing any properties specific to a particular item type I'd recommend checking the MessageClass property first to make sure that you deal with a mail item and the required property exists for the item chosen.
See How to determine type of an outlook item in python for more information.
Another possible reason is security triggers in the Outlook object model. Read more about that in the Outlook Object Model Security Warnings article. Possible routes to avoid such triggers are:
Use a low-level API on which Outlook is based on - Extended MAPI. Or just consider using any wrapper around that API such as Redemption.
Use components for turning on/off security issues in Outlook, see Outlook Security Manager.
Use group policy to configure security issues when dealing with OOM.
Install any antivirus software with latest databases.

smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server. Python

I am attempting to run a python script to automate sending emails but I keep running into this error.
Any suggestions on how to fix this?
import smtplib
from email import message
from_addr = 'myemail#gmail.com'
to_addr = 'myemail#gmail.com'
subject = 'Test Email'
body = 'Test'
msg = message.Message()
msg.add_header('from', from_addr)
msg.add_header('to', to_addr)
msg.add_header('subject', subject)
msg.set_payload(body)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.login(from_addr, 'password')
The error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program `Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\smtplib.py", line 716, in login`
raise SMTPNotSupportedError(
smtplib.SMTPNotSupportedError: SMTP AUTH extension not supported by server.
I'm not shure, but for gmail you need https://myaccount.google.com/lesssecureapps Allow less secure apps: ON setting.
Or you need Google APIs for authentication: https://developers.google.com/gmail/api/quickstart/python
I was having the same issue. Google recent ended support for "allow less secure apps" and the commonly recommended answer of using an app password also does not appear to work reliably either (it will work sometimes, but then gmail will start rejecting the authentication a day or two later).
Google's suggested quickstart guide (https://developers.google.com/gmail/api/guides/sending) is incomplete but does eventually work. In that process, you will get an error because you did not redirect the URI. You'll need to add this to the approved URIs within your google API console and then follow the link again.
You will hit a 2nd issue because your user will not be approved to use your own project. You will need to add your gmail account as a test user.
Once you have the URI forwarding correctly and you are approved to use your own app, you will then get an error (HTTP Error 403) because the Gmail API will not be activated. Go back to the google API console and enable the Gmail API. Finally, you can run the quickstart.py file again and it will complete without errors.
I have not yet tested this solution for actually sending email, but it does appear to grant your app full access to the email account that you set up. I also do not know if this is a long term solution or if there are tokens which will time out.
Based on the difficulty of this, it seems that finding another email SMTP service may be a better solution if that's possible for your situation.
You can get your app password to login your account via smtp. This solves the issue for less secure app feature.
Coming towards your error it might be due to something is not supported but here I see you have not started TLS connection. Starting TLS connection can solve this error if there's no other issue.
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(from_addr, 'password') # here you can need to use app password
This should solve the error most of the time if other things are correct.

"Failed RTM connect" error when trying to connect to Slack with RTM API

I'm using the following Python code from Slack's "Migrating to 2.x" github docs
from slackclient import SlackClient
slack_token = os.environ["SLACK_API_TOKEN"]
client = SlackClient(slack_token)
def say_hello(data):
if 'Hello' in data['text']:
channel_id = data['channel']
thread_ts = data['ts']
user = data['user']
client.api_call('chat.postMessage',
channel=channel_id,
text="Hi <#{}>!".format(user),
thread_ts=thread_ts
)
if client.rtm_connect():
while client.server.connected is True:
for data in client.rtm_read():
if "type" in data and data["type"] == "message":
say_hello(data)
else:
print "Connection Failed"
For the SLACK_API_TOKEN, I am using the Bot User OAuth Access Token for my app, found here:
The error I am getting is the following:
Failed RTM connect
Traceback (most recent call last):
File "/Users/.../slackbot/slackbot_env/lib/python3.8/site-packages/slackclient/client.py", line 140, in rtm_connect
self.server.rtm_connect(use_rtm_start=with_team_state, **kwargs)
File "/Users/.../slackbot/slackbot_env/lib/python3.8/site-packages/slackclient/server.py", line 168, in rtm_connect
raise SlackLoginError(reply=reply)
slackclient.server.SlackLoginError
Connection Failed
Why am I getting this error?!?!?!
Other context:
I am on a Mac, unlike others who have had issues online using Windows
machines.
I am running the code locally, in a virtual env, via
python script.py in my terminal.
I last successfully ran this in December, and have seen that Slack dropped support for the RTM API (?) Dec 31st 2019?
The app has been reinstalled to my workspace, and the keys did not change.
I think it may be something I need to configure/change/set/refresh on the api.slack.com/apps side, since it broke without any code changes occurring.
Why am I focusing on debugging the example for 1.x? My code was previously working using rtm_connect / 1.x using the same commands as the example code, and without any code changes it has stopped working. My code and the example code yield the same errors, so I'm using the sample code to make debugging easier. I'd like to fix this before starting the process of migrating to 2.x, so I can start with working code before embarking on a long series of changes that can introduce their own errors.
I do not think this issue is related to the Bot User OAuth Access Token, in my view you are using the right one (xoxb-). However, this issue might be related to the Slack App. Note that RTM isn't supported for the new Slack App granular scopes (see python client issue #584 and node client issue #921). If you want to use RTM, you should create rather a classic slack app with the OAuth Scope bot.
I not sure if this is the reason, but I ran into the same issues before.
The answer I found on the Slack Github is that new xoxob-* doesn't support RTM.
Please reference this web:
- https://github.com/slackapi/python-slackclient/issues/326.
So I use my OAuth Access Token instead of Bot User OAuth Access Token.

Accessing Office 365 ProPlus OneDrive folder using the official Python SDK

We are currently trying to access a folder of an Office 365 ProPlus tenant using the official OneDrive SDK for Python (https://github.com/OneDrive/onedrive-sdk-python). One of our clients would like to use a OneDrive folder as a way of storing and sharing programmatically generated files, therefore, we would like to provide basic file operations.
We have a working solution for a personal OneDrive account, however, when we try to apply the same approach for their OneDrive, we face an issue during the authentication process.
We asked them to register the application in the Azure AD following the steps in the official documentation. Next, they sent us the redirect URI, client ID and client secret that we included in our script. We are trying to use the following code:
redirect_uri = 'REDIRECT_URI'
client_secret = 'CLIENT_SECRET'
client_id='CLIENT_ID'
discovery_uri = 'https://api.office.com/discovery/'
auth_server_url='https://login.microsoftonline.com/common/oauth2/authorize'
auth_token_url='https://login.microsoftonline.com/common/oauth2/token'
http_provider = onedrivesdk.HttpProvider()
auth_provider = onedrivesdk.AuthProvider(http_provider,
client_id,
auth_server_url=auth_server_url,
auth_token_url=auth_token_url)
auth_url = auth_provider.get_auth_url(redirect_uri)
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)
However, we get the following error message when executing the last line:
Traceback (most recent call last):
File "onedrive-test.py", line 25, in
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)
File "/home/username/.local/lib/python3.6/site-packages/onedrivesdk/helpers/GetAuthCodeServer.py",
line 60, in get_auth_code
s = GetAuthCodeServer((host_address, port), code_acquired, GetAuthCodeRequestHandler)
File "/home/username/.local/lib/python3.6/site-packages/onedrivesdk/helpers/GetAuthCodeServer.py",
line 76, in init
HTTPServer.init(self, server_address, RequestHandlerClass)
File "/usr/lib/python3.6/socketserver.py", line 453, in init
self.server_bind()
File "/usr/lib/python3.6/http/server.py", line 136, in server_bind
socketserver.TCPServer.server_bind(self)
File "/usr/lib/python3.6/socketserver.py", line 467, in server_bind
self.socket.bind(self.server_address)
socket.gaierror: [Errno -2] Name or service not known
We also tried opening the auth_url manually, which took us one step further, but still could not authenticate the application with the following error:
AADSTS50020: User account 'USER ACCOUNT' from identity provider
'live.com' does not exist in tenant 'TENANT NAME' and cannot access
the application 'CLIENT ID' in that tenant. The account needs to be
added as an external user in the tenant first. Sign out and sign in
again with a different Azure Active Directory user account.
We have two questions:
What might casue the first error? This is the comment (see below) that can be found in the readme of the SDK about using the GetAuthCodeServer class. It seems to us that the server cannot be run. Are there any not explicitly defined dependencies that we should be aware of before trying to run the webserver? (We are running the script on Ubuntu 18.10)
If you want to remove some of that manual work, you can
use the helper class GetAuthCodeServer. That helper class spins up a
webserver, so this method cannot be used on all environments.
With respect to the second issue, can you recommend proper material for configuring OneDrive for Business for our use-case? We went through a lot of documentation, but after long hours of research, we still could not find the correct way to fix that issue, especially since we do not have direct acces to the tenant and we cannot easily experiment with things. We would need to give a step-by-step cookbook to our client to set up everything on their side.
Any help would be much appreciated! :)

BadParametersError: Invalid signature when using OVH Python wrapper

I'm using OVH API along with python wrapper:
https://pypi.python.org/pypi/ovh
When trying to execute this code:
import ovh
client = ovh.Client()
# Print nice welcome message
print "Welcome", client.get('/me')['firstname']
I get this error:
Traceback (most recent call last):
File "index.py", line 6, in <module>
print "Welcome", client.get('/me')['firstname']
File "/home/rubinhozzz/.local/lib/python2.7/site-packages/ovh/client.py", line 290, in get
return self.call('GET', _target, None, _need_auth)
File "/home/rubinhozzz/.local/lib/python2.7/site-packages/ovh/client.py", line 419, in call
raise BadParametersError(json_result.get('message'))
ovh.exceptions.BadParametersError: Invalid signature
My info is saved in the ovh.conf as the documentation suggests.
[default]
; general configuration: default endpoint
endpoint=ovh-eu
[ovh-eu]
application_key=XXXlVy5SE7dY7Gc5
application_secret=XXXdTEBKHweS5F0P0tb0lfOa8GoQPy4l
consumer_key=pscg79fXXX8ESMIXXX7dR9ckpDR7Pful
It looks that I can connect but when trying to use the services like for instance "/me", the error raises!
It is difficult to reproduce the issue because it requires an application key and it seems that it is only granted to existing customers of OVH. I couldn't even see a link to an account registration page on their site.
By looking at the code of the call() method in /ovh/client.py, it seems that their server doesn't recognise the format or the content off the signature sent by your script. According to the inline documentation the signature is generated from these parameters:
application_secret
consumer_key
METHOD
full request url
body
server current time (takes time delta into account)
Since your call is identical to the example code provided on the OVH Python package web page, the last four parameters should be valid. In that case it looks like either the application secret or the customer key (or both) in your config file are not correct.
See also the documentation on OVH site under the 'Signing requests' heading. They explain how the signature is made and what it should look like.
Perhaps try to re-create a new application API to obtain new key and secret and make sure you copy them without any additional character.

Categories