pax_global_header 0000666 0000000 0000000 00000000064 14765120533 0014520 g ustar 00root root 0000000 0000000 52 comment=6fc33471bb4d8229ca7417998cf3ff6b76f319af
email-oauth2-proxy-2025-03-14/ 0000775 0000000 0000000 00000000000 14765120533 0015562 5 ustar 00root root 0000000 0000000 email-oauth2-proxy-2025-03-14/.gitignore 0000664 0000000 0000000 00000003535 14765120533 0017560 0 ustar 00root root 0000000 0000000 # Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# Custom for this repository
emailproxy.config
versions
launchd
.idea
*.config
*.iml
email-oauth2-proxy-2025-03-14/LICENSE 0000664 0000000 0000000 00000026135 14765120533 0016576 0 ustar 00root root 0000000 0000000 Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
email-oauth2-proxy-2025-03-14/README.md 0000664 0000000 0000000 00000106321 14765120533 0017044 0 ustar 00root root 0000000 0000000 # Email OAuth 2.0 Proxy
Transparently add OAuth 2.0 support to IMAP/POP/SMTP client applications, scripts or any other email use-cases that don't support this authentication method.
## Motivation and capabilities
Email services that support IMAP, POP and/or SMTP access are increasingly requiring the use of OAuth 2.0 to authenticate connections, but not all clients support this method.
This tool creates a local proxy that intercepts the traditional IMAP/POP/SMTP authentication commands and transparently replaces them with the appropriate SASL (X)OAuth 2.0 commands and credentials.
Your email client can continue to use the `login` or `auth`/`authenticate` options, with no need to make it aware of OAuth's existence.
The proxy works in the background with a menu bar/taskbar helper or as a headless system service, and is compatible with macOS, Windows and Linux.
### Example use-cases
- You need to use an Office 365 email account, but don't get on with Outlook.
The email client you like doesn't support OAuth 2.0, which became mandatory [in January 2023](https://techcommunity.microsoft.com/t5/exchange-team-blog/basic-authentication-deprecation-in-exchange-online-september/ba-p/3609437) ([September 2024 for personal Hotmail/Outlook accounts](https://support.microsoft.com/en-us/office/modern-authentication-methods-now-needed-to-continue-syncing-outlook-email-in-non-microsoft-email-apps-c5d65390-9676-4763-b41f-d7986499a90d); [September 2025 for O365 SMTP](https://techcommunity.microsoft.com/t5/exchange-team-blog/exchange-online-to-retire-basic-auth-for-client-submission-smtp/ba-p/4114750)).
- You used to use Gmail via IMAP/POP/SMTP with your raw account credentials (i.e., your real password), but cannot do this now that Google has disabled this method, and don't want to use an [App Password](https://support.google.com/accounts/answer/185833) (or cannot enable this option).
- You have an account already set up in an email client, and you need to switch it to OAuth 2.0 authentication.
You can edit the server details, but the client forces you to delete and re-add the account to enable OAuth 2.0, and you don't want to do this.
- You have made your own script or application that sends or receives email, but it doesn't support OAuth 2.0, and you don't want to have to modify it to implement this.
- You work with multiple services or applications that use IMAP/POP/SMTP, and you don't want to have to set up OAuth 2.0 independently for each one.
In all of these cases and more, this proxy can help – just follow the instructions below to get started.
Visit the [Discussions pages](https://github.com/simonrob/email-oauth2-proxy/discussions) for help with any configuration or setup problems, or [open an issue](https://github.com/simonrob/email-oauth2-proxy/issues) to report bugs or make suggestions.
For commercial support or feature requests, please also consider [sponsoring this project](https://github.com/sponsors/simonrob?frequency=one-time).
## Getting started
Begin by downloading the proxy via one of the following methods:
- Pick a pre-built release for your platform (macOS or Windows; no installation needed); or,
- Install from PyPI: set up using
python -m pip install emailproxy\[gui\], download the sample emailproxy.config file, then python -m emailproxy to run; or,
- Clone or download (and star :-) the GitHub repository, then:
python -m pip install -r requirements-core.txt -r requirements-gui.txt to install requirements, and python emailproxy.py to run.
Next, edit the sample `emailproxy.config` file to add configuration details for each email server and account that you want to use with the proxy.
[Guidance and example account configurations](https://github.com/simonrob/email-oauth2-proxy/blob/main/emailproxy.config) are provided for Office 365, Gmail and several other providers, though you will need to insert your own client credentials for each one (see the [client credentials documentation](#oauth-20-client-credentials) below for help doing this).
You can remove details from the sample configuration file for services you don't use, or add additional ones for any other OAuth 2.0-authenticated IMAP/POP/SMTP servers you would like to use with the proxy.
You can now start the proxy: depending on which installation option you chose, either launch the application or use the appropriate run command listed above.
A menu bar/taskbar icon should appear.
If this does not happen, see the [dependencies and setup](#dependencies-and-setup) section for help resolving this.
For additional options, including fully headless deployments and integration with a secrets manager, see the [optional arguments](#optional-arguments-and-configuration) and [advanced configuration](#advanced-configuration) sections.
Finally, open your email client and configure its server details to match the ones you set in the proxy's configuration file.
The correct server to use with an account is identified using the port number you select in your client – for example, to use the sample Office 365 details, this would be `127.0.0.1` on port `1993` for IMAP, port `1995` for POP and port `1587` for SMTP.
The proxy supports multiple accounts simultaneously, and all accounts associated with the same provider can share the same proxy server.
The local connection in your email client should be configured as unencrypted to allow the proxy to operate, but the connection between the proxy and your email server is always secure (implicit SSL/TLS for IMAP and POP; implicit or explicit (STARTTLS) SSL/TLS for SMTP).
See the [sample configuration file](https://github.com/simonrob/email-oauth2-proxy/blob/main/emailproxy.config) for additional documentation about advanced features, including local encryption, account configuration inheritance and support for running in a container.
The first time your email client makes a request you should see a notification from the proxy about authorising your account.
Click the proxy's menu bar icon, select your account name in the `Authorise account` submenu, and then log in via the popup browser window that appears.
The window will close itself once the process is complete.
See the various [optional arguments](#optional-arguments-and-configuration) for support completing authentication if running without a GUI.
After successful authentication and authorisation you should have IMAP/POP/SMTP access to your account as normal.
Make sure you keep the proxy running at all times to allow it to authorise your email client's background activity – enable `Start at login` from the proxy's menu, or see the [auto-start instructions](#starting-the-proxy-automatically) about how to configure this in various different setups.
After your accounts are fully set-up and authorised, no further proxy interaction should be required unless your account needs authorising again.
It will notify you if this is the case.
### OAuth 2.0 client credentials
As part of the proxy setup process you need to provide an OAuth 2.0 `client_id` and (in many cases) a `client_secret` to allow it to authenticate with email servers on your behalf.
If you have an existing client ID and secret for a desktop app, you can use these directly in the proxy.
If this is not possible, you can also reuse the client ID and secret from any email client that supports IMAP/POP/SMTP OAuth 2.0 authentication with the email server you would like to connect to (such as [the](https://github.com/mozilla/releases-comm-central/blob/812b7c9068ca5cac0580b0ddbea8e34c141cd441/mailnews/base/src/OAuth2Providers.jsm) [many](https://github.com/mozilla/releases-comm-central/blob/master/mailnews/base/src/OAuth2Providers.sys.mjs) [existing](https://github.com/Foundry376/Mailspring/blob/master/app/internal_packages/onboarding/lib/onboarding-constants.ts) [open](https://gitlab.gnome.org/GNOME/evolution-data-server/-/blob/master/CMakeLists.txt) [source](https://gitlab.gnome.org/GNOME/gnome-online-accounts/-/blob/master/meson_options.txt) [clients](https://github.com/M66B/FairEmail/blob/master/app/src/main/res/xml/providers.xml) with OAuth 2.0 support), but please do this with care and restraint as access through reused tokens will be associated with the token owner rather than your own client.
If you do not want to use credentials from an existing client you will need to register your own.
The process to do this is different for each provider, but the registration guides for several common ones are linked here.
In all cases, when registering, make sure your client is set up to use an OAuth scope that will give it permission to access IMAP/POP/SMTP as desired.
It is also highly recommended to use a scope that will grant "offline" access (i.e., a way to [refresh the OAuth 2.0 authentication token](https://oauth.net/2/refresh-tokens/) without user intervention).
The [sample configuration file](https://github.com/simonrob/email-oauth2-proxy/blob/main/emailproxy.config) provides example scope values for several common providers.
- Office 365: register a new [Microsoft identity application](https://learn.microsoft.com/entra/identity-platform/quickstart-register-app).
- Gmail / Google Workspace: register a [Google API desktop app client](https://developers.google.com/identity/protocols/oauth2/native-app).
- Outlook / Hotmail (personal accounts): If you are part of the Microsoft 365 Developer Programme or have an Azure account (including free accounts), you can create your own app registration in the Entra admin centre – see [this discussion](https://github.com/simonrob/email-oauth2-proxy/discussions/301) for a guide.
If not, you will need to reuse an existing client ID – see, for example, [this sample configuration](https://github.com/simonrob/email-oauth2-proxy/issues/297#issuecomment-2424200404).
- AOL and Yahoo Mail (and subproviders such as AT&T) are not currently allowing new client registrations with the OAuth email scope – the only option here is to reuse the credentials from an existing client that does have this permission.
The proxy supports [Google Cloud service accounts](https://cloud.google.com/iam/docs/service-account-overview) for access to Google Workspace Gmail.
It also supports the [client credentials grant (CCG)](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-client-creds-grant-flow), [resource owner password credentials grant (ROPCG)](https://learn.microsoft.com/entra/identity-platform/v2-oauth-ropc) and [device authorisation grant (DAG)](https://tools.ietf.org/html/rfc8628) OAuth 2.0 flows, and [certificate credentials (JWT)](https://learn.microsoft.com/entra/identity-platform/certificate-credentials).
Please note that currently only Office 365 / Outlook is known to support the CCG, ROPCG, DAG and certificate credentials methods.
See the [sample configuration file](https://github.com/simonrob/email-oauth2-proxy/blob/main/emailproxy.config) for further details.
## Optional arguments and configuration
When starting the proxy there are several optional arguments that can be set to customise its behaviour.
- `--no-gui` will launch the proxy without an icon, which allows it to be run as a `systemctl` service as demonstrated in [this example](https://github.com/simonrob/email-oauth2-proxy/issues/2#issuecomment-839713677), or fully headless as demonstrated in [various](https://github.com/michaelstepner/email-oauth2-proxy-aws) [other](https://github.com/blacktirion/email-oauth2-proxy-docker) subprojects.
Please note that unless you also specify one of the authorisation options below, or are using an OAuth 2.0 flow that does not require user authorisation, this mode is only of use if you have already authorised your accounts through the proxy in GUI mode, or are loading a proxy configuration file that already contains the cached authorisation tokens.
If you do not set `--external-auth` or `--local-server-auth`, accounts that have not yet been authorised (or for whatever reason require re-authorisation) will time out when authenticating, and an error will be printed to the log.
- `--external-auth` configures the proxy to present an account authorisation URL to be opened in an external browser and wait for you to copy+paste the post-authorisation result.
In GUI mode this can be useful in situations where the proxy's own browser window does not have access to some required authentication attribute of your typical setup.
In no-GUI mode this option allows you to authenticate accounts entirely externally (unlike `--local-server-auth`, which starts a local web server), though you will need to monitor the proxy's output and/or log for authentication notifications.
After visiting the link provided and authorising account access, paste the final URL from your browser's address bar back into the proxy's popup window (GUI mode) or the terminal (no-GUI mode) to give it access to transparently proxy your login.
You should ignore any browser error message that is shown (e.g., `unable to connect`); the important part is the URL itself.
This argument is identical to enabling external authorisation mode from the `Authorise account` submenu of the proxy's menu bar icon.
- `--local-server-auth` is similar to `--external-auth`, but instead instructs the proxy to temporarily start an internal web server to receive authentication responses.
The `--external-auth` option is ignored in this mode.
To authorise your account, visit the link that is provided, authenticate, and proceed until you are presented with a success webpage from the proxy.
Please note that while authentication links can actually be visited from anywhere to log in and authorise access, by default the final redirection target (i.e., a link starting with your account's `redirect_uri` value) must be accessed from the machine hosting the proxy itself so that the local server can receive the authorisation result.
See the [sample configuration file](https://github.com/simonrob/email-oauth2-proxy/blob/main/emailproxy.config) for advanced options to configure this (via `redirect_listen_address`).
- `--config-file` allows you to specify the location of a [configuration file](https://github.com/simonrob/email-oauth2-proxy/blob/main/emailproxy.config) that the proxy should load.
If this argument is not provided, the proxy will look for `emailproxy.config` in its working directory.
By default, the proxy also saves cached OAuth 2.0 tokens back to this file, so it must be writable.
See the `--cache-store` option if you would rather store configuration and cached values separately.
- `--cache-store` is used to specify a separate location in which to cache authorised OAuth 2.0 tokens and associated metadata.
The value of this argument can either be the full path to a local file (which must be writable), or an identifier for an external store such as a secrets manager (see the [advanced configuration](#advanced-configuration) section).
If this argument is not provided, credentials will be cached in the current configuration file.
- `--log-file` allows you to specify the location of a file to send log output to (full path required).
Log files are rotated at 32MB and 10 older log files are kept.
This option overrides the proxy's default behaviour, which varies by platform (see [below](#troubleshooting) for details).
- `--debug` enables debug mode, printing more verbose output to the log as [discussed below](#troubleshooting).
This argument is identical to enabling debug mode from the proxy's menu bar icon.
If needed, debug mode can also be toggled at runtime by sending the signal `SIGUSR1` (e.g.: `pkill -SIGUSR1 -f emailproxy`).
### Advanced configuration
The [example configuration file](https://github.com/simonrob/email-oauth2-proxy/blob/main/emailproxy.config) contains further documentation for many additional features of the proxy, including catch-all (wildcard) accounts, locally-encrypted connections, advanced OAuth 2.0 flows, integration with a secrets manager and more.
If you are using the proxy in a non-GUI environment it is possible to skip installation of dependencies that apply only to the interactive version.
To do this, install via `python -m pip install emailproxy` (i.e., without the `[gui]` variant option), and pass the [`--no-gui`](#optional-arguments-and-configuration) argument when starting the proxy.
Please note that the proxy was designed as a GUI-based tool from the outset due to the inherently interactive nature of the most common OAuth 2.0 authorisation flows, and there are limits to its ability to support fully no-GUI operation.
See the [optional arguments and configuration](#optional-arguments-and-configuration) section of this file for further details.
If your network requires connections to use an existing proxy, you can instruct the script to use this by setting the [proxy handler](https://docs.python.org/3/library/urllib.request.html#urllib.request.ProxyHandler) environment variable `https_proxy` (and/or `http_proxy`) – for example, `https_proxy=localhost python -m emailproxy`.
After installing its requirements, the proxy script can be packaged as a single self-contained executable using [Nuitka](https://nuitka.net/) (`nuitka --standalone --macos-create-app-bundle emailproxy.py`) or [pyinstaller](https://pyinstaller.org/) (`pyinstaller --onefile emailproxy.py`[[1]](#f1)).
A pyinstaller-packaged version is provided automatically for each [release](https://github.com/simonrob/email-oauth2-proxy/releases).
Python 3.7 or later is required to run the proxy.
The [python2 branch](https://github.com/simonrob/email-oauth2-proxy/tree/python2) provides minimal compatibility with python 2.7, but with a limited feature set, and no ongoing maintenance.
See [issue 38](https://github.com/simonrob/email-oauth2-proxy/issues/38) for further discussion.
### Starting the proxy automatically
In order for the proxy to authenticate background requests from your email client it needs to be kept running constantly.
The easiest way to do this is to start the script automatically.
In GUI mode the proxy has basic support for this built-in: click its menu bar icon and then select `Start at login`, which will stop the terminal instance and restart the script, configuring it to run each time you log in.
On macOS, if you are presented with a prompt about file access here, make sure you grant this so that python can run the proxy in the background.
For more advanced configurations, you may want to customise the startup behaviour and edit the script's parameters.
The method to achieve this differs depending on whether you are using macOS, Windows or Linux.
On macOS, the file `~/Library/LaunchAgents/ac.robinson.email-oauth2-proxy.plist` is used to configure automatic starting of the proxy.
If you stop the proxy's service (i.e., `Quit Email OAuth 2.0 Proxy` from the menu bar), you can restart it using `launchctl start ac.robinson.email-oauth2-proxy` from a terminal.
You can stop, disable or remove the service from your startup items either via the menu bar icon option, or using `launchctl unload `_`[plist path]`_.
If you edit the plist file manually, make sure you `unload` and then `load` it to update the system with your changes.
If the `Start at login` option appears not to be working for you on macOS, see the [known issues section](#known-issues) for potential solutions.
On Windows the auto-start functionality is achieved via a shortcut in your user account's startup folder.
Pressing `⊞ Win` + `r` and entering `shell:startup` (and then clicking OK) will open this folder – from here you can either double-click the `ac.robinson.email-oauth2-proxy.cmd` file to relaunch the proxy, edit it to configure, or delete this file (either manually or by deselecting the option in the proxy's menu) to remove the proxy from your startup items.
On Linux this feature assumes that your system supports XDG Autostart.
A Desktop Entry file `ac.robinson.email-oauth2-proxy.desktop` will be created in `~/.config/autostart/`.
Use the proxy's menu option (or manually remove this file) to prevent it starting when you log in.
It is also possible to run the proxy as a service (e.g., via `systemctl`) – see the `--no-gui` mode option above for more details.
## Troubleshooting
If you encounter problems using the proxy, enabling `Debug mode` from the menu or passing `--debug` as a command line argument will print all client–proxy–server communication to your system log to help identify the issue.
This will include all commands to and responses from the server (and also as a result the content of your email messages).
On macOS this can be viewed using Console.app or `log stream --predicate 'subsystem == "ac.robinson.email-oauth2-proxy"' --level=debug`.
On Windows a file `emailproxy.log` will be created in the same location as the proxy (see also the `--log-file` option).
On Linux you can use, for example, `tail -f /var/log/syslog | grep "Email OAuth 2.0 Proxy"`.
Please note that debug mode may also result in your login credentials being printed to the log (though this is avoided where possible).
However, it is worth pointing out that because account authorisation with the remote email server is handled entirely through OAuth 2.0 in a web browser, while the username you set in your email client must be correct, the password used for the local IMAP/POP/SMTP connection to the proxy can be anything you like, and does not need to be the one you actually use to log in to your account (though it must be the same value each time, or you will be asked to re-authenticate repeatedly by the proxy).
The password you provide via your email client is used only to encrypt and decrypt the OAuth 2.0 authentication token that the proxy transparently sends to the server on your behalf.
Because of this, if you are concerned about debug mode and security you can use a test password for debugging and then replace it with a secure password (and authenticate again) once set up.
It is often helpful to be able to view the raw connection details when debugging (i.e., without using your email client).
This can be achieved using `telnet`, [PuTTY](https://www.chiark.greenend.org.uk/~sgtatham/putty/) or similar.
For example, to test the Office 365 IMAP server from the [example configuration](https://github.com/simonrob/email-oauth2-proxy/blob/main/emailproxy.config), first open a connection using `telnet 127.0.0.1 1993`, and then send a login command: `a1 login e@mail.com password`, replacing `e@mail.com` with your email address, and `password` with any value you like during testing (see above for why the password is irrelevant).
If you have already authorised your account with the proxy you should see a response starting with `a1 OK`; if not, this command should trigger a notification from the proxy about authorising your account.
Note that POP and SMTP are different protocols, and while they can be tested in this way, they require different commands to be sent – see [this issue comment](https://github.com/simonrob/email-oauth2-proxy/issues/251#issuecomment-2133976839) for further details.
If you are using a [secure local connection](https://github.com/simonrob/email-oauth2-proxy/blob/main/emailproxy.config) the interaction with the remote email server is the same as above, but you will need to use a local debugging tool that supports encryption.
The easiest approach here is to use [OpenSSL](https://www.openssl.org/): `openssl s_client -crlf -connect 127.0.0.1:1993`.
If you are having trouble actually connecting to the proxy, it is always worth double-checking the `local_address` values that you are using.
The [sample configuration file](https://github.com/simonrob/email-oauth2-proxy/blob/main/emailproxy.config) sets this parameter to `127.0.0.1` for all servers.
If you remove this value and do not provide your own, the proxy defaults to `::` – in most cases this resolves to `localhost` for both IPv4 and IPv6 configurations, but it is possible that this differs depending on your environment.
If you are unable to connect to the proxy from your email client, first try specifying this value explicitly – see the [sample configuration file](https://github.com/simonrob/email-oauth2-proxy/blob/main/emailproxy.config) for further details about how to do this.
Please try setting and connecting to both IPv4 (i.e., `127.0.0.1`) and IPv6 (i.e., `::1`) loopback addresses before reporting any connection issues with the proxy.
### Dependencies and setup
On macOS the proxy's setup and installation instructions should automatically bundle or install all required dependencies.
Any error messages you may encounter (for example, with your `pip` version and `cryptography`, or `pillow` and `imagingft` dependencies, or [macOS SSL failures](https://github.com/simonrob/email-oauth2-proxy/issues/14#issuecomment-1077379254)) normally give clear explanations of the issues and point to instructions for resolving these problems.
Please [open an issue](https://github.com/simonrob/email-oauth2-proxy/issues) if you encounter any other problems here.
When first launching on Linux in GUI mode you may encounter errors similar to `Namespace […] not available`, issues with the task bar icon display, or no browser popup when attempting to authorise your accounts.
This is caused by missing dependencies for [pystray](https://github.com/moses-palmer/pystray/) and [pywebview](https://github.com/r0x0r/pywebview/), which are used to display the menu bar icon and authentication windows.
See the [pywebview dependencies](https://pywebview.flowrl.com/guide/installation.html#dependencies) and [pystray FAQ](https://pystray.readthedocs.io/en/latest/faq.html) pages and [existing](https://github.com/simonrob/email-oauth2-proxy/issues/1#issuecomment-831746642) [closed](https://github.com/simonrob/email-oauth2-proxy/issues/136#issuecomment-1430417456) [issues](https://github.com/simonrob/email-oauth2-proxy/issues/305#issuecomment-2482989955) in this repository for a summary and suggestions about how to resolve this.
A similar issue may occur on Windows with the [pythonnet](https://github.com/pythonnet/pythonnet) package, which is required by [pywebview](https://github.com/r0x0r/pywebview).
The [pythonnet installation instructions](https://github.com/pythonnet/pythonnet/wiki/Installation) may offer alternative ways to install this package if the default installation fails.
Note that the public releases of pythonnet can take some time to be compatible with the latest major python release, so it can be worth using a slightly older version of python, or a pre-release version of pythonnet.
### Known issues
- With some combinations of operating systems, web engines and virtual environments, keyboard control or input to the proxy's popup authorisation window may not always work.
On Windows this is normally limited to keyboard shortcuts (i.e., copy/paste), but in some virtual environments on macOS the entire keyboard may not work.
As a workaround, the proxy will enable pywebview's debug mode when you run the proxy itself in debug mode, which should allow you to use the right-click context menu to copy/paste to enter text.
If you are unable to proceed with popup-based authentication even with this workaround, it is worth trying the proxy's `--external-auth` or `--local-server-auth` options.
- If the authorisation window fails to render due to an issue with hardware acceleration (for example: `MESA: error: ZINK: failed to choose pdev`), you can try disabling hardware rendering by setting the environment variable `LIBGL_ALWAYS_SOFTWARE=1`.
You may also wish to try disabling the DMABUF renderer in WebKit with `WEBKIT_DISABLE_DMABUF_RENDERER=1`.
- On macOS (10.14 and later), you may find that when first running the proxy as a service you need to manually load its launch agent in order to trigger a file access permission prompt.
You will know intervention is necessary if the proxy exits (rather than restarts) the first time you click `Start at login` from its menu bar icon.
To resolve this, exit the proxy and then run `launchctl load ~/Library/LaunchAgents/ac.robinson.email-oauth2-proxy.plist` from a terminal.
A permission pop-up should appear requesting file access for python.
Once this has been approved, the proxy's menu bar icon will appear as normal.
In some cases — particularly when running the proxy in a virtual environment, or using the built-in macOS python, rather than the python.org version, or installations managed by, e.g., homebrew, pyenv, etc. — the permission prompt does not appear.
If this happens it is worth first trying to `unload` and then `load` the service via `launchctl`.
If this still does not cause the prompt to appear, the only currently-known resolution is to run the proxy outside of a virtual environment and manually grant Full Disk Access to your python executable via the privacy settings in the macOS System Preferences.
You may also need to edit the proxy's launch agent plist file, which is found at the location given [in the command above](#starting-the-proxy-automatically), to set the path to your python executable – it must be the real path rather than a symlink (the `readlink` command can help here).
Fortunately this is a one-time fix, and once the proxy loads successfully via this method you will not need to adjust its startup configuration again (except perhaps when upgrading to a newer major macOS version, in which case just repeat the procedure).
### Other problems
Please feel free to [open an issue](https://github.com/simonrob/email-oauth2-proxy/issues) reporting any bugs you find, or [submit a pull request](https://github.com/simonrob/email-oauth2-proxy/pulls) to help improve this tool.
## Advanced features
The [plugins variant of the proxy](https://github.com/simonrob/email-oauth2-proxy/tree/plugins) has an additional feature that enables the use of separate scripts to modify IMAP/POP/SMTP commands when they are received from the client or server before passing through to the other side of the connection.
This allows a wide range of additional capabilities or triggers to be added the proxy.
For example, the [IMAPIgnoreSentMessageUpload plugin](https://github.com/simonrob/email-oauth2-proxy/blob/plugins/plugins/IMAPIgnoreSentMessageUpload.py) intercepts any client commands to add emails to the IMAP sent messages mailbox, which resolves message duplication issues for servers that automatically do this when emails are received via SMTP (e.g., Office 365, Gmail, etc.).
The [IMAPCleanO365ATPLinks plugin](https://github.com/simonrob/email-oauth2-proxy/blob/plugins/plugins/IMAPCleanO365ATPLinks.py) restores "Safe Links" modified by Microsoft Defender for Office 365 to their original URLs, while the [IMAPRegexContentReplacer plugin](https://github.com/simonrob/email-oauth2-proxy/blob/plugins/plugins/IMAPRegexContentReplacer.py) lets you match and remove/replace any content in the message.
The [SMTPBlackHole plugin](https://github.com/simonrob/email-oauth2-proxy/blob/plugins/plugins/SMTPBlackHole.py) gives the impression emails are being sent but actually silently discards them, which is useful for testing email sending tools.
See the [documentation and examples](https://github.com/simonrob/email-oauth2-proxy/tree/plugins/plugins) for further details, additional sample plugins and setup instructions.
## Potential improvements (pull requests welcome)
- Full feature parity on different platforms (e.g., live menu updating; monitoring network status; clickable notifications)
- Switch to asyncio? (with Python 3.12, [PEP 594](https://peps.python.org/pep-0594/) removed the asyncore package that the proxy is built upon – currently mitigated by the use of [pyasyncore](https://pypi.org/project/pyasyncore/))
- Remote STARTTLS for IMAP/POP?
## Related projects and alternatives
Michael Stepner has created a [Terraform configuration](https://github.com/michaelstepner/email-oauth2-proxy-aws) that helps run this proxy on a lightweight cloud server (AWS EC2).
Thiago Macieira has provided a [makefile and systemd configuration files](https://github.com/thiagomacieira/email-oauth2-proxy/tree/Add_a_Makefile_and_systemd_configuration_files_to_install_system_wide).
For Docker, Moriah Morgan has an [example configuration](https://github.com/blacktirion/email-oauth2-proxy-docker).
If you already use postfix, the [sasl-xoauth2](https://github.com/tarickb/sasl-xoauth2) plugin is probably a better solution than running this proxy.
Similarly, if you use an application that is able to handle OAuth 2.0 tokens but just cannot retrieve them itself, then [pizauth](https://github.com/ltratt/pizauth), [mailctl](https://github.com/pdobsan/mailctl) or [oauth-helper-office-365](https://github.com/ahrex/oauth-helper-office-365) may be more appropriate.
There are also dedicated helpers available for specific applications (e.g., [mutt_oauth2](https://gitlab.com/muttmua/mutt/-/blob/master/contrib/mutt_oauth2.py)), and several open-source email clients that support OAuth 2.0 natively (e.g., [Thunderbird](https://www.thunderbird.net/), [Mailspring](https://getmailspring.com/), [FairEmail](https://email.faircode.eu/), [Evolution](https://wiki.gnome.org/Apps/Evolution), etc.).
[DavMail](http://davmail.sourceforge.net/) is an alternative to this proxy that takes the same approach of providing a local IMAP/POP/SMTP server (and more) for Exchange/Office 365, though it does this by translating these protocols into Exchange API calls rather than proxying the connection.
That approach is very useful in situations where server-side IMAP/POP/SMTP is not supported or enabled, or the full Exchange capabilities are needed, but it has limitations in terms of speed and the number of email messages that can be retrieved.
This proxy was developed to work around these limitations for providers that do support IMAP/POP/SMTP natively.
## License
[Apache 2.0](https://github.com/simonrob/email-oauth2-proxy/blob/main/LICENSE)
---
1. If you are packaging the GUI version of the proxy using pyinstaller, you may need to add `--hidden-import timeago.locales.en_short` until [this `timeago` issue](https://github.com/hustcc/timeago/issues/40) is resolved.
email-oauth2-proxy-2025-03-14/SECURITY.md 0000664 0000000 0000000 00000000705 14765120533 0017355 0 ustar 00root root 0000000 0000000 # Security Policy
## Supported Versions
Using the [latest release of the proxy](https://github.com/simonrob/email-oauth2-proxy/releases/latest) is always recommended.
Any security issues found in prior versions should be reported, but may only be fixed if they affect the latest version.
## Reporting a Vulnerability
Report vulnerabilities or security issues using [GitHub's security tools](https://github.com/simonrob/email-oauth2-proxy/security).
email-oauth2-proxy-2025-03-14/emailproxy.config 0000664 0000000 0000000 00000066445 14765120533 0021161 0 ustar 00root root 0000000 0000000 [Email OAuth 2.0 Proxy configuration file]
documentation = This is a sample Email OAuth 2.0 Proxy configuration file. Configure the proxy by adding items in the
[Server setup] and [Account setup] sections below. You may delete any servers or accounts that you do not intend to
use. Documentation is provided inline, with example setups for Gmail and Office 365 (though you will need to enter
your own desktop app API client credentials in the accounts section). Use the `Reload configuration file` menu
option or send a SIGHUP signal (or quit the proxy before editing, then restart) to apply any changes.
format = This file's format is documented at docs.python.org/library/configparser#supported-ini-file-structure. Values
that span multiple lines should be indented deeper than the first line of their key (as in this comment). Quoting
of values is not required. Documentation sections can be removed if needed (though it is advisable to leave these
in place for reference) - thw only required sections are the individual server and account items of your setup.
warning = Do not commit changes to this file into a public repository (e.g., GitHub, etc). While the proxy encrypts the
OAuth 2.0 tokens it obtains and saves on your behalf, it cannot protect these against offline brute-force attacks.
[Server setup]
documentation = Local servers are specified as demonstrated below where, for example, the section heading [IMAP-1993]
gives the type (which can be IMAP, POP or SMTP) and the local port number to listen on (i.e., 1993, etc). The local
port must be above 1023 (unless the proxy script is run via sudo), below 65536, and unique across local servers.
Multiple accounts can share the same server, however. Each server section must specify the `server_address` and
`server_port` of the remote server that it will be proxying - you can obtain these values from your email provider,
or use the details below (examples are given for Office 365 / Outlook and Gmail).
To allow the proxy to operate, your email client must be set up to use an unencrypted connection for IMAP/SMTP/POP
(i.e., no STARTTLS or SSL/TLS, just plain login credentials). The proxy will create a secure connection on your
behalf to the remote server from the outset by default (i.e., implicit SSL/TLS); see below if STARTTLS is required.
Server customisation:
- If your SMTP server uses the STARTTLS approach, add `server_starttls = True`, as shown in the [SMTP-1587] example
below (assumed to be False otherwise). With this parameter set, STARTTLS negotiation will be handled by the proxy
on your behalf (i.e., do not enable STARTTLS in your client). IMAP/POP STARTTLS are not currently supported.
- The `local_address` property can be used to set an IP address or hostname for the proxy to listen on. Both IPv4
and IPv6 are supported. If not specified, this value is set to `::` (i.e., dual-stack IPv4/IPv6 on all interfaces).
When a hostname is set the proxy will first resolve this to an IP address, preferring IPv6 over IPv4 if both are
available. When running in an IPv6 environment with dual-stack support, the proxy will attempt to listen on both
IPv4 and IPv6 hosts simultaneously. Note that tools such as `netstat` do not always accurately show dual-stack mode;
if you are having trouble connecting to the proxy, it is worth actually testing both IPv4 and IPv6 connections.
Advanced server configuration:
- As explained above, you should not enable STARTTLS in your local client, as the proxy handles secure communication
with the server on your behalf. However, if your client does not allow STARTTLS to be disabled, you can in addition
set `local_starttls = True` to emulate STARTTLS locally to allow your client to connect. If you set this parameter,
you must also provide a local certificate as outlined below.
- In the standard configuration the channel between your email client and the proxy is unencrypted. This is not
normally of any concern since the proxy is typically a local-only service. However, if you prefer, you may provide
a `local_certificate_path` (e.g., /etc/letsencrypt/live/mail.example.net/fullchain.pem) and `local_key_path` (e.g.,
/etc/letsencrypt/live/mail.example.net/privkey.pem) for the server you are using the proxy with, and it will use
these to set up a secure connection between itself and your email client.
Advanced feature - proxy plugins:
- Plugins are an advanced feature that enable the use of separate scripts to modify IMAP/POP/SMTP commands when they
are received from the client or server before passing through to the other side of the connection. For more details
about how to install and enable this feature, see the additional documentation and range of sample plugins explained
at https://github.com/simonrob/email-oauth2-proxy/tree/plugins/plugins#email-oauth-20-proxy-plugins
[IMAP-1993]
documentation = *** note: this server will work for both Office 365 and personal Outlook/Hotmail accounts ***
server_address = outlook.office365.com
server_port = 993
local_address = 127.0.0.1
[POP-1995]
documentation = *** note: this server will work for both Office 365 and personal Outlook/Hotmail accounts ***
server_address = outlook.office365.com
server_port = 995
local_address = 127.0.0.1
[SMTP-1587]
documentation = *** note: this server will work for both Office 365 and personal Outlook/Hotmail accounts ***
server_address = smtp-mail.outlook.com
server_port = 587
server_starttls = True
local_address = 127.0.0.1
[IMAP-2993]
server_address = imap.gmail.com
server_port = 993
local_address = 127.0.0.1
[POP-2995]
server_address = pop.gmail.com
server_port = 995
local_address = 127.0.0.1
[SMTP-2465]
server_address = smtp.gmail.com
server_port = 465
local_address = 127.0.0.1
[Account setup]
documentation = Accounts are specified using your email address as the section heading (e.g., [your.email@gmail.com],
etc, below). Account usernames (i.e., email addresses) must be unique - only one entry per account is permitted.
Each account section must provide values for at least `token_url`, `oauth2_scope` and `client_id`. Depending on the
OAuth 2.0 flow you are using, other values may also be required (see examples below). If you are adding an account
for a service other than the examples shown below then the provider's documentation should provide these details.
You will also need to add your own `client_id` and (in many cases) `client_secret` values as indicated below. These
can either be reused from an existing source (such as an email client that supports OAuth 2.0), or you can register
your own desktop app client credentials. See https://developers.google.com/identity/protocols/oauth2/native-app
and the Microsoft link below for details. Multiple accounts on the same server can use the same values for the
`client_id` and `client_secret` properties; just duplicate these in each account's entry below, or see the advanced
`allow_catch_all_accounts` option. Note that while there are example account configurations for AOL and Yahoo Mail
below, these services are not currently accepting new OAuth 2.0 client registrations with the mail access scope, so
reusing existing credentials is the only option here.
Once the proxy is correctly configured, after the first successful use of an account its access token details will
be cached for future use, encrypted with the IMAP/POP/SMTP password you used in your email client. By default this
configuration file is reused for caching (so it must be writable), but you can specify a different location or
method using the proxy's `--cache-store` parameter. See below for advanced use of this option to integrate with a
secrets manager service. You should not add or edit cached values manually (i.e.,`token_salt`, `token_iterations`,
`access_token`, `access_token_expiry`, `refresh_token` and `last_activity`); the proxy handles this.
The password used in your email client is not used for authentication with the actual email server (this is done via
OAuth 2.0 in a web browser), so it can be different to your real account password, which is helpful for debugging.
Please note, though, that all clients that use a particular account via the proxy should use the same IMAP/POP/SMTP
password to avoid repeated re-authentication requests (which is the proxy's default behaviour when credential
decryption fails). See the proxy's README.md file for more information and the end of this file for further options.
Office 365 / Outlook customisation:
- Unlike other providers, Office 365 / Outlook requires an OAuth 2.0 scope that explicitly grants `offline_access`
(shown in the examples below) in order to allow the proxy to refresh its access token on your behalf. The proxy will
still without this parameter, but you will need to re-authenticate extremely often (about once per hour).
- The example Office 365 / Outlook configuration entries below use an OAuth 2.0 scope that clearly specifies IMAP,
POP and SMTP permission. If you do not require one or more of these protocols, you may remove the relevant values to
ensure access tokens obtained on your behalf are as precisely-targeted as possible. Conversely, it is also possible
to replace these specific scopes with the more generic `https://outlook.office365.com/.default`. Switching to a
broader scope value may also be needed if you are using Microsoft services delivered by a regional provider (e.g.,
21Vianet). See: https://github.com/simonrob/email-oauth2-proxy/issues/255 for more details and discussion.
- By default, new Entra (Azure AD) clients are accessible only within your own tenant. If you are registering a new
client to use with the proxy (and do not want to make it available outside your own organisation) you will need to
replace `common` with your tenant ID in the `permission_url` and `token_url` values below. Alternatively, you can
reuse credentials from an existing client registration (see the proxy's README.md file), or configure your client as
a multi-tenant application. For more detail about this, and guides for setting up your desktop app client, see the
documentation at https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app.
- Office 365 shared mailboxes are supported: add an account entry here using the email address of the shared
mailbox as the account name. When asked to authenticate, log in as the user that access has been delegated to.
Note that Office 365 no-longer supports the `authorised.user@example.com/delegated.mailbox` username syntax.
- It is possible to create Office 365 / Outlook OAuth 2.0 clients that do not require a secret to be sent. If this
is the case for your setup, delete the `client_secret` line from your account's configuration entry (do not leave
the default value).
- To use Office 365 certificate credentials instead of a client secret, delete the `client_secret` line and instead
provide a `jwt_certificate_path` (e.g., /path/to/certificate.pem) and `jwt_key_path` (e.g., /path/to/key.pem).
Further documentation and examples can be found at https://github.com/simonrob/email-oauth2-proxy/pull/247.
- The proxy supports the client credentials grant (CCG) and resource owner password credentials grant (ROPCG) OAuth
2.0 flows (both currently only known to be available for Office 365). To use either of these flows, add an account
entry as normal, but do not add a `permission_url` value (it does not apply, and its absence signals to the proxy to
use the appropriate token retrieval mechanism). For CCG, set `oauth2_scope = https://outlook.office365.com/.default`
and `oauth2_flow = client_credentials`. For ROPCG, set `oauth2_flow = password` (and use a standard scope value). An
example is given for both methods towards the end of the sample account entries below.
- WARNING: Please note that by default the CCG flow has essentially no local access control when creating new
accounts (no user consent is involved, so the proxy cannot validate login attempts unless an account entry
already exists in its configuration file). Using the CCG flow with the proxy in a publicly-accessible context
is not advised. This is especially important when using the proxy's catch-all feature (which is likely to be
the case given the typical use-cases for the CCG flow). Because of this, you are highly encouraged to enable
the proxy's secret encryption option - see `encrypt_client_secret_on_first_use` at the end of this file. In
addition, if you are using the proxy in an environment where there is any possibility of malicious access
attempts before the first valid login, pre-encrypting account entries is highly recommended. See the example
script at https://github.com/simonrob/email-oauth2-proxy/issues/61#issuecomment-1259110336.
- The proxy supports the device authorisation grant (DAG) OAuth 2.0 flow (currently only known to be available for
Office 365 / Outlook), which may better suit headless systems. To use this flow, set `oauth2_flow = device`. With
this flow, the proxy receives authorisation responses directly from the service provider, so no `redirect_uri` is
needed. An example account configuration is given below. For additional customisation, the proxy modifications and
scripts demonstrated at https://github.com/simonrob/email-oauth2-proxy/pull/317 show how the DAG flow authorisation
message could be pushed to a separate device, which may be useful when running the proxy headless or without a GUI.
Gmail customisation:
- The proxy supports the use of service accounts with Gmail for Google Workspace (note: normal Gmail accounts do not
support this method). To use this option, add an account entry as normal, but do not add a `permission_url` value
(it does not apply, and its absence signals to the proxy to use the appropriate token retrieval mechanism). Set
`oauth2_flow = service_account`. The service account key itself can either be referenced in an external file, or
pasted directly into the account entry. For the file approach, set `client_id = file` and `client_secret` to the
full path to the JSON key file. To include the key directly, set `client_id = key`, then paste the full contents of
your service account's JSON key as the value for `client_secret`, making sure all lines are indented by at least one
space (so that the proxy can tell they are all part of one value). An example is given for both methods towards the
end of the sample account entries below. Note that when creating the account entry here and when logging in from an
email client, the username you should use is the account you are trying to access, not the service account user
(i.e., do not use the auto-generated address that is similar to `your-user@your-project.iam.gserviceaccount.com`).
- WARNING: Please note that the same potential security issues outlined above with O365's CCG flow also apply
to the service account method: there is essentially no local access control when creating new accounts. Using
a service account with the proxy in a publicly-accessible context is not advised. You are highly encouraged to
enable the proxy's secret encryption option (see `encrypt_client_secret_on_first_use` at the end of this file)
and consider pre-encrypting account entries. A sample pre-encryption script is provided for reference at
https://github.com/simonrob/email-oauth2-proxy/issues/212#issuecomment-1867557029
Advanced account configuration:
- For most configurations the default `redirect_uri` value of `http://localhost` is correct, unless you have
explicitly set the OAuth 2.0 client configuration with your provider to use a different address for this purpose
(e.g., redirecting via an external domain). If this is the case, you will need to manually redirect this to the
proxy. Please note that in most cases the address is indeed `http://`, not `https://`.
- When using the `--local-server-auth` option you will need to either run the proxy with additional privileges to
use the implicit default port 80 (e.g., via sudo) or specify a different port (and/or a different host if needed) -
for example, `redirect_uri = http://localhost:8080`. In addition, if you are using this proxy option in a setup that
is not directly exposed (such as a container or private network) you may also need to map `redirect_uri` traffic via
a private address. Once this is configured (via external tools/rules), instruct the proxy to listen here using the
parameter `redirect_listen_address` - for example, `redirect_listen_address = http://10.0.0.0:8080`.
- Please note that when using `--local-server-auth` the proxy will start/stop a new local server for each incoming
authentication request, and does not explicitly handle repeated requests or multiple accounts authenticating using
the same address. To avoid clashes, it is recommended that each account has a unique `redirect_uri` (or
`redirect_listen_address`) value, for example by using a different port for each account.
Integration with a secrets manager:
- The proxy caches authenticated OAuth 2.0 tokens and associated metadata back into this configuration file by
default, but can alternatively be configured to use either a separate local file (via `--cache-store /path/to/file`)
or a secrets manager service for remote token storage. Currently only AWS Secrets Manager is supported. To use this
feature, set the proxy's `--cache-store` parameter to either a full AWS ARN or a secret name, prefixing the value
with `aws:` to identify its type to the proxy. If not already present, you must also install the AWS SDK for Python
(`python -m pip install boto3`) and set up authentication credentials (including a region) - see the documentation
at https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#configuration. The minimum required
permissions for the associated AWS IAM user are `secretsmanager:GetSecretValue` and `secretsmanager:PutSecretValue`.
If the named AWS Secret does not yet exist, the proxy will attempt to create it; in this case, the permission
`secretsmanager:CreateSecret` is also required.
[your.office365.or.outlook.address@example.com]
permission_url = https://login.microsoftonline.com/common/oauth2/v2.0/authorize
token_url = https://login.microsoftonline.com/common/oauth2/v2.0/token
oauth2_scope = https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/POP.AccessAsUser.All https://outlook.office.com/SMTP.Send offline_access
redirect_uri = http://localhost
client_id = *** your client id here ***
client_secret = *** your client secret here (remove this entire line if a secret is not required) ***
[your.email@gmail.com]
permission_url = https://accounts.google.com/o/oauth2/auth
token_url = https://oauth2.googleapis.com/token
oauth2_scope = https://mail.google.com/
redirect_uri = http://localhost
client_id = *** your client id here ***
client_secret = *** your client secret here ***
[your.email@yahoo.co.uk]
permission_url = https://api.login.yahoo.com/oauth2/request_auth
token_url = https://api.login.yahoo.com/oauth2/get_token
oauth2_scope = mail-w
redirect_uri = http://localhost
client_id = *** your client id here - note that as new client registrations are not permitted for Yahoo, you will need to reuse an existing client ID (see the proxy's readme) ***
client_secret = *** your client secret here ***
[your.email@aol.com]
permission_url = https://api.login.aol.com/oauth2/request_auth
token_url = https://api.login.aol.com/oauth2/get_token
oauth2_scope = mail-w
redirect_uri = http://localhost
client_id = *** your client id here - note that as new client registrations are not permitted for AOL, you will need to reuse an existing client ID (see the proxy's readme) ***
client_secret = *** your client secret here ***
[dag.flow.configured.address@outlook.com]
permission_url = https://login.microsoftonline.com/common/oauth2/v2.0/devicecode
token_url = https://login.microsoftonline.com/common/oauth2/v2.0/token
oauth2_scope = https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/POP.AccessAsUser.All https://outlook.office.com/SMTP.Send offline_access
oauth2_flow = device
client_id = *** your client id here ***
client_secret = *** your client secret here (remove this entire line if a secret is not required) ***
[ccg.flow.configured.address@your-tenant.com]
documentation = *** note: this is an advanced O365 account example; in most cases you want the version above instead ***
token_url = https://login.microsoftonline.com/*** your tenant id here ***/oauth2/v2.0/token
oauth2_scope = https://outlook.office365.com/.default
oauth2_flow = client_credentials
client_id = *** your client id here ***
client_secret = *** your client secret here (remove this entire line if a secret is not required) ***
[ropcg.flow.configured.address@your-tenant.com]
documentation = *** note: this is an advanced O365 account example; in most cases you want the version above instead ***
token_url = https://login.microsoftonline.com/*** your tenant id here ***/oauth2/v2.0/token
oauth2_scope = https://outlook.office365.com/IMAP.AccessAsUser.All https://outlook.office365.com/POP.AccessAsUser.All https://outlook.office365.com/SMTP.Send offline_access
oauth2_flow = password
client_id = *** your client id here ***
client_secret = *** your client secret here (remove this entire line if a secret is not required) ***
[service.account.accessible.address@your-domain.com]
documentation = *** note: this is an advanced Google account example; in most cases you want the version above instead ***
token_url = https://oauth2.googleapis.com/token
oauth2_scope = https://mail.google.com/
oauth2_flow = service_account
client_id = file
client_secret = *** your /path/to/service-account-key.json here ***
[service.account.accessible.address@your-domain.org]
documentation = *** note: this is an advanced Google account example; in most cases you want the version above instead ***
token_url = https://oauth2.googleapis.com/token
oauth2_scope = https://mail.google.com/
oauth2_flow = service_account
client_id = key
client_secret = *** your pasted service account JSON key file contents here,
making sure to indent all lines by at least one space ***
[Advanced proxy configuration]
documentation = The parameters below control advanced options for the proxy. In most cases you will not need to modify
the values in this section. If any of these values are not found, the proxy will assume the default value, which
can be found in the example config file (https://github.com/simonrob/email-oauth2-proxy/blob/main/emailproxy.config)
Parameter documentation:
- delete_account_token_on_password_error (default = True): Once an account has been authenticated via the proxy, if
there is a login attempt with a different (local) password, its default behaviour is to remove the saved OAuth 2.0
credentials and present a new authentication request. This is a sensible default for local use as it means that a
password typo does not give the false impression that the proxy has somehow made the account inaccessible. However,
if the proxy is used in a headless (often also public-facing) context, where authentication flows are more likely to
be laborious or need administrator intervention, this can potentially result in a denial-of-service issue, whether
malicious or not. It can also be the source of confusion if using a client (such as Firefox) that stores a separate
password per protocol for each account, but does not make this clear when changing account passwords. Set this
option to False and the proxy will instead return an error when an incorrect password is provided. For accounts
using the O365 CCG flow or a Google Cloud service account this option will be overridden and always set to False.
- encrypt_client_secret_on_first_use (default = False): The proxy encrypts sensitive configuration values (e.g.,
cached access tokens) using the password that is given when accessing an account via IMAP/POP/SMTP. It does not do
this for values that are not sensitive. In the most common operation mode (i.e., interactively authorising account
access), the `client_secret` value falls into this category - it is not actually secret, and there is no real need
to prevent access to it. However, when using the client credentials grant (CCG) flow or a service account, there is
no user involved, and possession of the secret grants full access to an account. If you use either of these methods
and it is possible that others may gain access to the proxy's configuration file; or, you are using catch-all
accounts (see below) and others may attempt to log in with accounts that the secret has access to but that you have
not yet set up with the proxy, set `encrypt_client_secret_on_first_use` to True and the proxy will replace the
`client_secret` value with a new property `client_secret_encrypted` at the next token refresh. Note that this option
is not fully compatible with `allow_catch_all_accounts` unless all accounts use the same login password, or you
undertake some additional manual setup configuration (see below for further details). In particular, if you are
using catch-all accounts or the proxy's `--cache-store` parameter you must manually remove unencrypted secrets from
the local configuration file after the encrypted secret has been created (i.e., this will not be automatic).
- use_login_password_as_client_credentials_secret (default = False): When using the O365 client credentials grant
(CCG) flow, rather than encrypting the client secret (see above), the proxy can be instructed to use the given
IMAP/POP/SMTP login password as the client secret. This approach removes the risk of storing the unencrypted client
secret in the proxy's configuration file, and also means there is no risk of unauthorised account access when using
the O365 CCG flow in conjunction with the proxy's catch-all mode (see below). To enable this option, set
`use_login_password_as_client_credentials_secret` to True. Note that if a `client_secret` value is present in your
account's configuration entry, that value will be used instead of the given IMAP/POP/SMTP login password even if
this option is enabled. To avoid this, remove the entire `client_secret` line from the configuration entry.
- allow_catch_all_accounts (default = False): The default behaviour of the proxy is to require a full separate
configuration file entry for each account. However, when proxying multiple accounts from the same domain it can be
cumbersome to have to create multiple near-identical configuration profiles. To simplify this the proxy supports
catch-all accounts when this option is set to True. Domain-level accounts are configured using section headings. For
example, add a section [@domain.com] with all of the standard required account values, and the proxy will intercept
authentication requests for all usernames at `domain.com`. Whenever a previously unseen account attempts to connect,
account authorisation will take place as normal, and the proxy will automatically create a new account-level section
that does not need to be configured manually. Any account-level configuration will override domain-level values
(except for account access and refresh tokens). If needed, the global catch-all section [@] can also be used. Please
note that this option is not fully compatible with `encrypt_client_secret_on_first_use` unless all IMAP/POP/SMTP
accounts at the same domain use the same password, or you undertake additional manual configuration steps - see the
discussion at https://github.com/simonrob/email-oauth2-proxy/issues/214#issuecomment-1861593781 for details.
[emailproxy]
delete_account_token_on_password_error = True
encrypt_client_secret_on_first_use = False
use_login_password_as_client_credentials_secret = False
allow_catch_all_accounts = False
email-oauth2-proxy-2025-03-14/emailproxy.py 0000664 0000000 0000000 00000625446 14765120533 0020346 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
"""A simple IMAP/POP/SMTP proxy that intercepts authenticate and login commands, transparently replacing them with OAuth
2.0 authentication. Designed for apps/clients that don't support OAuth 2.0 but need to connect to modern servers."""
__author__ = 'Simon Robinson'
__copyright__ = 'Copyright (c) 2024 Simon Robinson'
__license__ = 'Apache 2.0'
__package_version__ = '2025.3.14' # for pyproject.toml usage only - needs to be ast.literal_eval() compatible
__version__ = '-'.join('%02d' % int(part) for part in __package_version__.split('.')) # ISO 8601 (YYYY-MM-DD)
import abc
import argparse
import base64
import binascii
import configparser
import contextlib
import datetime
import enum
import errno
import io
import ipaddress
import json
import logging
import logging.handlers
import os
import pathlib
import platform
import plistlib
import queue
import re
import select
import signal
import socket
import ssl
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import warnings
import wsgiref.simple_server
import wsgiref.util
import zlib
# asyncore is essential, but has been deprecated and will be removed in python 3.12 (see PEP 594)
# pyasyncore is our workaround, so suppress this warning until the proxy is rewritten in, e.g., asyncio
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
import asyncore
# for encrypting/decrypting the locally-stored credentials
from cryptography.fernet import Fernet, MultiFernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
# by default the proxy is a GUI application with a menu bar/taskbar icon, but it is also useful in 'headless' contexts
# where not having to install GUI-only requirements can be helpful - see the proxy's readme (the `--no-gui` option)
MISSING_GUI_REQUIREMENTS = []
no_gui_parser = argparse.ArgumentParser(add_help=False)
no_gui_parser.add_argument('--no-gui', action='store_false', dest='gui')
no_gui_args = no_gui_parser.parse_known_args()[0]
if no_gui_args.gui:
try:
# noinspection PyUnresolvedReferences
import pystray # the menu bar/taskbar GUI
except Exception as gui_requirement_import_error: # see #204 - incomplete pystray installation can throw exceptions
MISSING_GUI_REQUIREMENTS.append(gui_requirement_import_error)
no_gui_args.gui = False # we need the dummy implementation
if not no_gui_args.gui:
class DummyPystray: # dummy implementation allows initialisation to complete (with skeleton to avoid lint warnings)
class Icon:
def __init__(self, *args, **kwargs):
pass
def run(self, *args, **kwargs):
pass
class Menu:
SEPARATOR = None
def __init__(self, *args, **kwargs):
pass
class MenuItem:
def __init__(self, *args, **kwargs):
pass
pystray = DummyPystray # this is just to avoid unignorable IntelliJ warnings about naming and spacing
del no_gui_parser
del no_gui_args
try:
# noinspection PyUnresolvedReferences
from PIL import Image, ImageDraw, ImageFont # draw the menu bar icon from the TTF font stored in APP_ICON
except ImportError as gui_requirement_import_error:
MISSING_GUI_REQUIREMENTS.append(gui_requirement_import_error)
try:
# noinspection PyUnresolvedReferences
import timeago # the last authenticated activity hint
except ImportError as gui_requirement_import_error:
MISSING_GUI_REQUIREMENTS.append(gui_requirement_import_error)
try:
# noinspection PyUnresolvedReferences
import webview # the popup authentication window (in default and GUI `--external-auth` modes only)
except ImportError as gui_requirement_import_error:
MISSING_GUI_REQUIREMENTS.append(gui_requirement_import_error)
try:
# pylint: disable-next=ungrouped-imports
import importlib.metadata as importlib_metadata # get package version numbers - available in stdlib from python 3.8
except ImportError:
try:
# noinspection PyUnresolvedReferences
import importlib_metadata
except ImportError as gui_requirement_import_error:
MISSING_GUI_REQUIREMENTS.append(gui_requirement_import_error)
try:
# noinspection PyUnresolvedReferences
import packaging.version # parse package version numbers - used to work around various GUI-only package issues
except ImportError as gui_requirement_import_error:
MISSING_GUI_REQUIREMENTS.append(gui_requirement_import_error)
# for macOS-specific functionality
if sys.platform == 'darwin':
try:
# PyUnresolvedReferences; see: youtrack.jetbrains.com/issue/PY-11963 (same for others with this suppression)
# noinspection PyPackageRequirements,PyUnresolvedReferences
import PyObjCTools.MachSignals # SIGTERM handling (only needed in GUI mode; `signal` is sufficient otherwise)
except ImportError as gui_requirement_import_error:
MISSING_GUI_REQUIREMENTS.append(gui_requirement_import_error)
try:
# noinspection PyPackageRequirements,PyUnresolvedReferences
import SystemConfiguration # network availability monitoring
except ImportError as gui_requirement_import_error:
MISSING_GUI_REQUIREMENTS.append(gui_requirement_import_error)
try:
# noinspection PyPackageRequirements
import AppKit # retina icon, menu update on click, native notifications and receiving system events
except ImportError as gui_requirement_import_error:
MISSING_GUI_REQUIREMENTS.append(gui_requirement_import_error)
class AppKit: # dummy implementation allows initialisation to complete
class NSObject:
pass
APP_NAME = 'Email OAuth 2.0 Proxy'
APP_SHORT_NAME = 'emailproxy'
APP_PACKAGE = 'ac.robinson.email-oauth2-proxy'
# noinspection SpellCheckingInspection
APP_ICON = b'''eNp1Uc9rE0EUfjM7u1nyq0m72aQxpnbTbFq0TbJNNkGkNpVKb2mxtgjWsqRJU+jaQHOoeMlVeoiCHqQXrwX/gEK9efGgNy+C4MWbHjxER
DCJb3dTUdQH733zvW/ezHszQADAAy3gIFO+kdbW3lXWAUgRs2sV02igdoL8MfLctrHf6PeBAXBe5OL27r2acry6hPprdLleNbbiXfkUtRfoeh0T4gaju
O6gT9TN5gEWo5GHGNjuXsVAPET+yuKmcdAAETaRR5BfuGuYVRCs/fQjBqGxt98En80/WzpYvaN3tPsvN4eufAWPc/r707dvLPyg/PiCcMSAq1n9AgXHs
MbeedvZz+zMH0YGZ99x7v9LxwyzpuBBpA8oTg9tB8kn0IiIHQLPwT9tuba4BfNQhervPZzdMGBWp1a9hJHYyHBeS2Y2r+I/2LF/9Ku3Q7tXZ9ogJKEEN
+EWbODRqpoaFwRXUJbDvK4Xghlek+WQ5KfKDM3N0dlshiQEQVHzuYJeKMxRVMNhWRISClYmc6qaUPxUitNZTdfz2QyfcmXIOK8xoOZKt7ViUkRqYXekW
J6Sp0urC5fCken5STr0KDoUlyhjVd4nxSUvq3tCftEn8r2ro+mxUDIaCMQmQrGZGHmi53tAT3rPGH1e3qF0p9w7LtcohwuyvnRxWZ8sZUej6WvlhXSk1
7k+POJ1iR73N/+w2xN0f4+GJcHtfqoWzgfi6cuZscC54lSq3SbN1tmzC4MXtcwN/zOC78r9BIfNc3M=''' # TTF ('e') -> zlib -> base64
CENSOR_CREDENTIALS = True
CENSOR_MESSAGE = b'[[ Credentials removed from proxy log ]]' # replaces actual credentials; must be a byte-type string
script_path = sys.executable if getattr(sys, 'frozen', False) else os.path.realpath(__file__) # for pyinstaller etc
if sys.platform == 'darwin' and '.app/Contents/MacOS/' in script_path: # pyinstaller .app binary is within the bundle
if float('.'.join(platform.mac_ver()[0].split('.')[:2])) >= 10.12: # need a known path (due to App Translocation)
script_path = pathlib.Path('~/.%s/%s' % (APP_SHORT_NAME, APP_SHORT_NAME)).expanduser()
else:
script_path = '.'.join(script_path.split('Contents/MacOS/')[0].split('/')[:-1])
script_path = os.getcwd() if __package__ is not None else os.path.dirname(script_path) # for packaged version (PyPI)
CONFIG_FILE_PATH = CACHE_STORE = os.path.join(script_path, '%s.config' % APP_SHORT_NAME)
CONFIG_SERVER_MATCHER = re.compile(r'^(?P(IMAP|POP|SMTP))-(?P\d+)$')
del script_path
MAX_CONNECTIONS = 0 # maximum concurrent IMAP/POP/SMTP connections; 0 = no limit; limit is per server
RECEIVE_BUFFER_SIZE = 65536 # number of bytes to try to read from the socket at a time (limit is per socket)
MAX_SSL_HANDSHAKE_ATTEMPTS = 1024 # number of attempts before aborting SSL/TLS handshake (max 10ms each); 0 = no limit
# IMAP/POP/SMTP require \r\n as a line terminator (we use lines only pre-authentication; afterwards just pass through)
LINE_TERMINATOR = b'\r\n'
LINE_TERMINATOR_LENGTH = len(LINE_TERMINATOR)
# seconds to wait before cancelling authentication requests (i.e., the user has this long to log in) - note that the
# actual server timeout is often around 60 seconds, so the connection may be closed in the background and immediately
# disconnect after login completes; however, the login credentials will still be saved and used for future requests
AUTHENTICATION_TIMEOUT = 600
TOKEN_EXPIRY_MARGIN = 600 # seconds before its expiry to refresh the OAuth 2.0 token
JWT_LIFETIME = 300 # seconds to add to the current time and use for the `exp` value in JWT certificate credentials
LOG_FILE_MAX_SIZE = 32 * 1024 * 1024 # when using a log file, its maximum size in bytes before rollover (0 = no limit)
LOG_FILE_MAX_BACKUPS = 10 # the number of log files to keep when LOG_FILE_MAX_SIZE is exceeded (0 = disable rollover)
IMAP_TAG_PATTERN = r'[!#$&\',-\[\]-z|}~]+' # https://ietf.org/rfc/rfc9051.html#name-formal-syntax
IMAP_AUTHENTICATION_REQUEST_MATCHER = re.compile('^(?P%s) (?P(LOGIN|AUTHENTICATE)) '
'(?P.*)$' % IMAP_TAG_PATTERN, flags=re.IGNORECASE)
IMAP_LITERAL_MATCHER = re.compile(r'^{(?P\d+)(?P\+?)}$')
IMAP_CAPABILITY_MATCHER = re.compile(r'^\* (?:OK \[)?CAPABILITY .*$', flags=re.IGNORECASE) # note: '* ' *and* '* OK ['
REQUEST_QUEUE = queue.Queue() # requests for authentication
RESPONSE_QUEUE = queue.Queue() # responses from user
QUEUE_SENTINEL = object() # object to send to signify queues should exit loops
MENU_UPDATE = object() # object to send to trigger a force-refresh of the GUI menu (new catch-all account added)
PLIST_FILE_PATH = pathlib.Path('~/Library/LaunchAgents/%s.plist' % APP_PACKAGE).expanduser() # launchctl file location
CMD_FILE_PATH = pathlib.Path('~/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Startup/%s.cmd' %
APP_PACKAGE).expanduser() # Windows startup .cmd file location
AUTOSTART_FILE_PATH = pathlib.Path('~/.config/autostart/%s.desktop' % APP_PACKAGE).expanduser() # XDG Autostart file
# noinspection SpellCheckingInspection
SECURE_SERVER_ICON = '''iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAApElEQVR4Ae3VsQ2DMBBA0ZQs4NIreA03GSbyAl6DAbyN+xvh
Ovp0yY9EkQZ8XELHSa+x0S9OAm75cT+F+UFm+vhbmClQLCtF+SnMNAji11lcz5orzCQopo21KJIn3FB37iuaJ9yRd+4zuicsSINViSesyEgbMtQcZgIE
TyNBsIQrXgdVS3h2hGdf+Apf4eIIF+ub16FYBhQd4ci3IiAOBP8/z+kNGUS6hBN6UlIAAAAASUVORK5CYII=''' # 22px SF Symbols lock.fill
EXTERNAL_AUTH_HTML_BASE = '''
Login authorisation request for %s
Click the following link to open your browser and approve the request:
%s
⧉
'''
EXTERNAL_AUTH_HTML = EXTERNAL_AUTH_HTML_BASE + '''After logging in and successfully
authorising your account, paste and submit the resulting URL from the browser's address bar using the box at the
bottom of this page to allow the %s script to transparently handle login requests on your behalf in future.
Note that your browser may show a navigation error (e.g., “localhost refused to connect”) after
successfully logging in, but the final URL is the only important part, and as long as this begins with the
correct redirection URI and contains a valid authorisation code your email client's request will succeed.''' + (
' If you are using Windows, submitting can take a few seconds.' if sys.platform == 'win32' else '') + '''
According to your proxy configuration file, the expected URL will be of the form:
%s […] code=[code] […]
'''
EXTERNAL_AUTH_DAG_HTML = EXTERNAL_AUTH_HTML_BASE + '''Enter the following code when
prompted:
%s
⧉
You can close this window once authorisation is complete.