Python 2.7 POP3_SSL Error connecting to Outlook Mailbox? - python

Some background: I am working on learning how to convert an app that uses a POP3 connection to use OAuth since Microsoft is dropping support for basic authentication in October. Initially I was using just POP3, but swapped to POP3_SSL after not being able to even enter a username. However, I've run across an issue authenticating with the password
import poplib
email_address = 'redacted#blank.com'
password = 'redacted'
pop3_server = 'outlook.office.com'
server = poplib.POP3(pop3_server)
server.set_debuglevel(1)
pop3_server_welcome_msg = server.getwelcome().decode('utf-8')
print(server.getwelcome().decode('utf-8'))
server.user(user=email_address)
server.pass_(password)
The error:
+OK The Microsoft Exchange POP3 service is ready. [UwBOADcAUABSADAANABDAEEAMAAxADkANgAuAG4AYQBtAHAAcgBkADAANAAuAHAAcgBvAGQALgBvAHUAdABsAG8AbwBrAC4AYwBvAG0A]
*cmd* 'USER redacted#blank.com'
*cmd* 'PASS redacted'
Traceback (most recent call last):
File "testScript.py", line 89, in <module>
server.pass_(password)
File "c:\python27\lib\poplib.py", line 197, in pass_
return self._shortcmd('PASS %s' % pswd)
File "c:\python27\lib\poplib.py", line 160, in _shortcmd
return self._getresp()
File "c:\python27\lib\poplib.py", line 136, in _getresp
raise error_proto(resp)
poplib.error_proto: -ERR Logon failure: unknown user name or bad password.
Copied project from here
Logging into the account via outlook the password works, but doesn't when running the script. If there is a step I have missed, please let me know. Thanks!

As it turns out, I was given the incorrect test email. The one I was using had advanced auth in place. Using an account with only basic auth works fine. Going to close this question.

Related

Sharepy library freezes at entering username in PyCharm

I'm trying to authenticate to SharePoint Online. Using sharepy v 2.0, pyCharm community edition, and python 3.9.
When I run:
'sharepy.connect('siteurl')'
From within PyCharm, Sharepy will freeze after I input my username in the run dialog box.
If I add the 'username' parameter and run it. Nothing happens. I'm never prompted for a password
If I use the console and enter in sharepy.connect('siteurl') then username and password (same goes for passing those parameters) I will get an error:
Traceback (most recent call last):
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\auth\adfs.py", line 75, in _get_token
token = root.find('.//wsse:BinarySecurityToken', ns).text
AttributeError: 'NoneType' object has no attribute 'text'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\session.py", line 15, in connect
return SharePointSession(site, auth=autoauth)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\session.py", line 61, in __init__
self.auth.login(self.site)
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\auth\adfs.py", line 27, in login
self._get_token()
File "C:\Users\Andrew\AppData\Local\Programs\Python\Python39\lib\site-packages\sharepy\auth\adfs.py", line 77, in _get_token
raise errors.AuthError('Token request failed. Invalid server response')
sharepy.errors.AuthError: Token request failed. Invalid server response
It should be noted I'm getting O365 from godaddy and the login page is federated? I think is the correct term.
According to the new release of Sharepy, this shouldn't matter.
Has anyone else had this freezing problem happen for them?
How would I authenticate with sharepoint using sharepy given my current situation?
The source of this problem ended up being GoDaddy. As we were federated using GoDaddy as the O365 provider. There was no way to authenticate correctly using sharepy.
The ultimate solution was to defederate away from GoDaddy (pretty easy to do thanks to this guy: Defederation Guide)
The reason we were unable to authenticate was because our provider redirects the login to their own login site. And unfortunately the sharepy builtin method of "auth" wouldn't work with GoDaddy.
I tested this theory before migrating away from GoDaddy. By using a fresh tenant. I also found that when you enable MFA the password/username method of authentication doesn't work.
NOTE: When new tenants are created they utilize a blanket security protocol which forces MFA. Even though MFA is shown as disabled in the Azure AD > Users section. To turn this off you must disable "Security Defaults": portal.azure.com > Azure Active Directory > Properties > "Manage security defaults" (at the bottom of the screen, its a small hyperlink).
A note on MFA and authentication with sharepy. There are methods to leave MFA enabled which work with other sharepoint/python things. I haven't tested them using sharepy yet, but will be turning on MFA and using one of the following methods:
App Password
Sharepoint API client secret
Azure App Registration (Azure App Reg)

Non-interactive authentication fails with WsTrust server issue MSIS7068

Setup:
Users are created on On-Prem AD and synced to Azure AD via Azure AD Connect
I have a single-tenant app set up on Azure AD
I created a user (On-Prem, synced to AAD) that can authenticate without MFA (we need to use username-password authentication due to an internal limitation).
Here is the non-interactive authentication code:
import msal
# create a public client app
authority_url = f"https://login.microsoftonline.com/{TENANT_ID}"
msal_app = msal.PublicClientApplication(client_id=CLIENT_ID, authority=authority_url)
# acquire token
token = msal_app.acquire_token_by_username_password(username=USERNAME, password=PASSWORD, scopes=SCOPES)
I'm getting the following error:
Traceback (most recent call last):
File "/./scripts/aad.py", line 8, in <module>
token = msal_app.acquire_token_by_username_password(
File "/usr/local/lib/python3.10/site-packages/msal/application.py", line 1420, in acquire_token_by_username_password
response = _clean_up(self._acquire_token_by_username_password_federated(
File "/usr/local/lib/python3.10/site-packages/msal/application.py", line 1447, in _acquire_token_by_username_password_federated
wstrust_result = wst_send_request(
File "/usr/local/lib/python3.10/site-packages/msal/wstrust_request.py", line 60, in send_request
return parse_response(resp.text)
File "/usr/local/lib/python3.10/site-packages/msal/wstrust_response.py", line 49, in parse_response
raise RuntimeError("WsTrust server returned error in RSTR: %s" % (error or body))
RuntimeError: WsTrust server returned error in RSTR: {'reason': 'MSIS7068: Access denied.', 'code': 'a:FailedAuthentication'}
Searching through Google I found that this can be caused by MFA, but the user is excluded from MFA. I've also verified that there are no Conditional Access policies in place to block the user accessing the app.
Using Interactive auth works as expected. Any ideas on how to get non-interactive auth to work or what might be the issue here?
First, no guesswork! You would need to login to Azure AD with elevated privilege (Security Reader at the least if not Global Administrator).
Go to Enterprise Applications and locate your application by client id.
One you are at the application, go to Sign-in tab/pane.
Review the sign-in activities. You should see the reason authentication failed in overview tab. Look at the Conditional Access tab and you will know if there is any policy that blocked the sign-in.
Take action based on what you identified in sign-in activity.
Okay, I am going to make an educated guess! When you login as non-interactive, you have two authentication choices - ROPC and Client Credential- both requires client_secret to be passed in the request but you have not! Since you are using username and password, it implies that msal is using ROPC and you must include client secret.

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.

python sharepoint - Error validating credentials due to invalid username or password

I want to automate downloading a zipfile on another organization's sharepoint site that they have shared with my organization, inviting us as a guest using a generic company email address so we can access the files. To gain access, I provide the company email address as username and its associated AD password which authenticates access through our MS 365 organization account.
This works fine manually, but when attempting to do it through shareplum I get a credentials error.
Here is my code:
from shareplum import Site
from shareplum import Office365
from shareplum.site import Version
sharepointUsername = 'elvis.presley#suspiciousminds.org'
sharepointPassword = 'oogabooga123'
sharepointSite = 'https://abc.sharepoint.com/sites/ClientLogin/Shared Documents/Graceland/'
authcookie = Office365(website, username=sharepointUsername,
password=sharepointPassword).GetCookies()
site = Site(sharepointSite, version=Version.v365, authcookie=authcookie)
And here is the error:
Traceback (most recent call last):
File "<string>", line 11, in <module>
File "C:\arcgispro-py3-clone2\lib\site-packages\shareplum\office365.py", line 88, in get_cookies
sectoken = self.get_security_token(self.username, self.password)
File "C:\arcgispro-py3-clone2\lib\site-packages\shareplum\office365.py", line 80, in get_security_token
raise Exception('Error authenticating against Office 365. Error from Office 365:', message[0].text)
Exception: ('Error authenticating against Office 365. Error from Office 365:', 'AADSTS50126: Error validating credentials due to invalid username or password.')
Any clue as why this is not working? I've checked the credentials several times using them to log in manually and it works every time (obviously the example does not have the real username/password)?
You’re not alone, this seems to be a common issue with shareplum over the past 6 months. There’s an open issue on GitHub. The code owner is aware and is having difficulty debugging the issue.
GitHub issue: https://github.com/jasonrollins/shareplum/issues/84
I recommend working closely with the code owner to debug and resolve the issue on GitHub, or using a different library/solution altogether. Another user commented on the issue and referenced a solution that utilizes the requests library to retrieve a file that you may find useful: https://github.com/jasonrollins/shareplum/issues/84#issuecomment-627986466 .

Google app engine send mail raises ApplicationError: 1 Internal Error

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

Categories