├── .github └── workflows │ └── pythonpublish.yml ├── .gitignore ├── LICENSE ├── MANIFEST.in ├── README.md ├── docs └── .gitkeep ├── gmailapi_backend ├── __init__.py ├── bin │ ├── __init__.py │ └── gmail_oauth2.py └── mail.py ├── pytest.ini ├── requirements.txt └── setup.py /.github/workflows/pythonpublish.yml: -------------------------------------------------------------------------------- 1 | # This workflows will upload a Python Package using Twine when a release is created 2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 3 | 4 | name: Upload Python Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | deploy: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Python 18 | uses: actions/setup-python@v1 19 | with: 20 | python-version: '3.x' 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install setuptools wheel twine 25 | - name: Build and publish 26 | env: 27 | TWINE_USERNAME: __token__ 28 | TWINE_PASSWORD: ${{ secrets.PYPI_API_KEY }} 29 | run: | 30 | python setup.py sdist bdist_wheel 31 | twine upload dist/* 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/vim,macos,emacs,python,virtualenv,visualstudiocode 3 | # Edit at https://www.gitignore.io/?templates=vim,macos,emacs,python,virtualenv,visualstudiocode 4 | 5 | ### Emacs ### 6 | # -*- mode: gitignore; -*- 7 | *~ 8 | \#*\# 9 | /.emacs.desktop 10 | /.emacs.desktop.lock 11 | *.elc 12 | auto-save-list 13 | tramp 14 | .\#* 15 | 16 | # Org-mode 17 | .org-id-locations 18 | *_archive 19 | 20 | # flymake-mode 21 | *_flymake.* 22 | 23 | # eshell files 24 | /eshell/history 25 | /eshell/lastdir 26 | 27 | # elpa packages 28 | /elpa/ 29 | 30 | # reftex files 31 | *.rel 32 | 33 | # AUCTeX auto folder 34 | /auto/ 35 | 36 | # cask packages 37 | .cask/ 38 | dist/ 39 | 40 | # Flycheck 41 | flycheck_*.el 42 | 43 | # server auth directory 44 | /server/ 45 | 46 | # projectiles files 47 | .projectile 48 | 49 | # directory configuration 50 | .dir-locals.el 51 | 52 | # network security 53 | /network-security.data 54 | 55 | 56 | ### macOS ### 57 | # General 58 | .DS_Store 59 | .AppleDouble 60 | .LSOverride 61 | 62 | # Icon must end with two \r 63 | Icon 64 | 65 | # Thumbnails 66 | ._* 67 | 68 | # Files that might appear in the root of a volume 69 | .DocumentRevisions-V100 70 | .fseventsd 71 | .Spotlight-V100 72 | .TemporaryItems 73 | .Trashes 74 | .VolumeIcon.icns 75 | .com.apple.timemachine.donotpresent 76 | 77 | # Directories potentially created on remote AFP share 78 | .AppleDB 79 | .AppleDesktop 80 | Network Trash Folder 81 | Temporary Items 82 | .apdisk 83 | 84 | ### Python ### 85 | # Byte-compiled / optimized / DLL files 86 | __pycache__/ 87 | *.py[cod] 88 | *$py.class 89 | 90 | # C extensions 91 | *.so 92 | 93 | # Distribution / packaging 94 | .Python 95 | build/ 96 | develop-eggs/ 97 | downloads/ 98 | eggs/ 99 | .eggs/ 100 | lib/ 101 | lib64/ 102 | parts/ 103 | sdist/ 104 | var/ 105 | wheels/ 106 | pip-wheel-metadata/ 107 | share/python-wheels/ 108 | *.egg-info/ 109 | .installed.cfg 110 | *.egg 111 | MANIFEST 112 | 113 | # PyInstaller 114 | # Usually these files are written by a python script from a template 115 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 116 | *.manifest 117 | *.spec 118 | 119 | # Installer logs 120 | pip-log.txt 121 | pip-delete-this-directory.txt 122 | 123 | # Unit test / coverage reports 124 | htmlcov/ 125 | .tox/ 126 | .nox/ 127 | .coverage 128 | .coverage.* 129 | .cache 130 | nosetests.xml 131 | coverage.xml 132 | *.cover 133 | .hypothesis/ 134 | .pytest_cache/ 135 | 136 | # Translations 137 | *.mo 138 | *.pot 139 | 140 | # Scrapy stuff: 141 | .scrapy 142 | 143 | # Sphinx documentation 144 | docs/_build/ 145 | 146 | # PyBuilder 147 | target/ 148 | 149 | # pyenv 150 | .python-version 151 | 152 | # pipenv 153 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 154 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 155 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 156 | # install all needed dependencies. 157 | #Pipfile.lock 158 | 159 | # celery beat schedule file 160 | celerybeat-schedule 161 | 162 | # SageMath parsed files 163 | *.sage.py 164 | 165 | # Spyder project settings 166 | .spyderproject 167 | .spyproject 168 | 169 | # Rope project settings 170 | .ropeproject 171 | 172 | # Mr Developer 173 | .mr.developer.cfg 174 | .project 175 | .pydevproject 176 | 177 | # mkdocs documentation 178 | /site 179 | 180 | # mypy 181 | .mypy_cache/ 182 | .dmypy.json 183 | dmypy.json 184 | 185 | # Pyre type checker 186 | .pyre/ 187 | 188 | ### Vim ### 189 | # Swap 190 | [._]*.s[a-v][a-z] 191 | [._]*.sw[a-p] 192 | [._]s[a-rt-v][a-z] 193 | [._]ss[a-gi-z] 194 | [._]sw[a-p] 195 | 196 | # Session 197 | Session.vim 198 | Sessionx.vim 199 | 200 | # Temporary 201 | .netrwhist 202 | 203 | # Auto-generated tag files 204 | tags 205 | 206 | # Persistent undo 207 | [._]*.un~ 208 | 209 | # Coc configuration directory 210 | .vim 211 | 212 | ### VirtualEnv ### 213 | # Virtualenv 214 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ 215 | pyvenv.cfg 216 | .env 217 | .venv 218 | env/ 219 | venv/ 220 | ENV/ 221 | env.bak/ 222 | venv.bak/ 223 | pip-selfcheck.json 224 | 225 | ### VisualStudioCode ### 226 | .vscode/* 227 | !.vscode/settings.json 228 | !.vscode/tasks.json 229 | !.vscode/launch.json 230 | !.vscode/extensions.json 231 | 232 | ### VisualStudioCode Patch ### 233 | # Ignore all local history of files 234 | .history 235 | 236 | # End of https://www.gitignore.io/api/vim,macos,emacs,python,virtualenv,visualstudiocode 237 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.md 2 | include *.txt 3 | include LICENSE 4 | # installation related 5 | exclude MANIFEST.in 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django Gmail API backend 2 | 3 | Email backend for Django which sends email via the Gmail API 4 | 5 | 6 | The simple SMTP protocol is disabled by default for Gmail users, since this 7 | is included in the Less Secure Apps (LSA) category. 8 | The advice is to use SMTP+OAuth or to use the Gmail API directly. 9 | This package implements the second option as a Django email backend. 10 | 11 | 12 | ## Installation 13 | 14 | Install the package 15 | 16 | ``` 17 | pip install django-gmailapi-backend 18 | ``` 19 | 20 | ## Configuration 21 | 22 | In your `settings.py`: 23 | 24 | 1. Add the module into the `INSTALLED_APPS` 25 | ```py 26 | INSTALLED_APPS = [ 27 | ... 28 | 'gmailapi_backend', 29 | ... 30 | ] 31 | ``` 32 | 33 | 2. Set the email backend 34 | ```py 35 | EMAIL_BACKEND = 'gmailapi_backend.mail.GmailBackend' 36 | ``` 37 | 38 | 3. Define the configuration parameters from your Gmail developer account (see next section) 39 | ```py 40 | GMAIL_API_CLIENT_ID = 'client_id' 41 | GMAIL_API_CLIENT_SECRET = 'client_secret' 42 | GMAIL_API_REFRESH_TOKEN = 'refresh_token' 43 | ``` 44 | 45 | ## Configure the Gmail credentials 46 | 47 | For using this package you need to obtain the OAuth credentials for a valid Gmail account. 48 | 49 | - More information on the Gmail API: https://developers.google.com/gmail/api/guides/sending 50 | - OAuth credentials for sending emails: https://github.com/google/gmail-oauth2-tools/wiki/OAuth2DotPyRunThrough 51 | 52 | This package includes the script linked in the documentation above, which simplifies 53 | the setup of the API credentials. The following outlines the key steps: 54 | 55 | 1. Create a project in the Google developer console, https://console.cloud.google.com/ 56 | 2. Enable the Gmail API 57 | 3. Create OAuth 2.0 credentials 58 | 4. Create a valid `refresh_token` using the helper script included in the package: 59 | ```sh 60 | gmail_oauth2 --generate_oauth2_token \ 61 | --client_id="" \ 62 | --client_secret="" \ 63 | --scope="https://www.googleapis.com/auth/gmail.send" 64 | ``` 65 | 66 | -------------------------------------------------------------------------------- /docs/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dolfim/django-gmailapi-backend/c96b7e712fa471b493552187b18d3e9e50c7d807/docs/.gitkeep -------------------------------------------------------------------------------- /gmailapi_backend/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '0.3.2' 2 | -------------------------------------------------------------------------------- /gmailapi_backend/bin/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dolfim/django-gmailapi-backend/c96b7e712fa471b493552187b18d3e9e50c7d807/gmailapi_backend/bin/__init__.py -------------------------------------------------------------------------------- /gmailapi_backend/bin/gmail_oauth2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # Copyright 2012 Google Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """Performs client tasks for testing IMAP OAuth2 authentication. 18 | 19 | To use this script, you'll need to have registered with Google as an OAuth 20 | application and obtained an OAuth client ID and client secret. 21 | See https://developers.google.com/identity/protocols/OAuth2 for instructions on 22 | registering and for documentation of the APIs invoked by this code. 23 | 24 | This script has 3 modes of operation. 25 | 26 | 1. The first mode is used to generate and authorize an OAuth2 token, the 27 | first step in logging in via OAuth2. 28 | 29 | oauth2 --user=xxx@gmail.com \ 30 | --client_id=1038[...].apps.googleusercontent.com \ 31 | --client_secret=VWFn8LIKAMC-MsjBMhJeOplZ \ 32 | --generate_oauth2_token 33 | 34 | The script will converse with Google and generate an oauth request 35 | token, then present you with a URL you should visit in your browser to 36 | authorize the token. Once you get the verification code from the Google 37 | website, enter it into the script to get your OAuth access token. The output 38 | from this command will contain the access token, a refresh token, and some 39 | metadata about the tokens. The access token can be used until it expires, and 40 | the refresh token lasts indefinitely, so you should record these values for 41 | reuse. 42 | 43 | 2. The script will generate new access tokens using a refresh token. 44 | 45 | oauth2 --user=xxx@gmail.com \ 46 | --client_id=1038[...].apps.googleusercontent.com \ 47 | --client_secret=VWFn8LIKAMC-MsjBMhJeOplZ \ 48 | --refresh_token=1/Yzm6MRy4q1xi7Dx2DuWXNgT6s37OrP_DW_IoyTum4YA 49 | 50 | 3. The script will generate an OAuth2 string that can be fed 51 | directly to IMAP or SMTP. This is triggered with the --generate_oauth2_string 52 | option. 53 | 54 | oauth2 --generate_oauth2_string --user=xxx@gmail.com \ 55 | --access_token=ya29.AGy[...]ezLg 56 | 57 | The output of this mode will be a base64-encoded string. To use it, connect to a 58 | IMAPFE and pass it as the second argument to the AUTHENTICATE command. 59 | 60 | a AUTHENTICATE XOAUTH2 a9sha9sfs[...]9dfja929dk== 61 | """ 62 | 63 | from __future__ import print_function 64 | 65 | import base64 66 | import imaplib 67 | import json 68 | from optparse import OptionParser 69 | import smtplib 70 | import sys 71 | import urllib 72 | 73 | import six 74 | 75 | 76 | def SetupOptionParser(): 77 | # Usage message is the module's docstring. 78 | parser = OptionParser(usage=__doc__) 79 | parser.add_option('--generate_oauth2_token', 80 | action='store_true', 81 | dest='generate_oauth2_token', 82 | help='generates an OAuth2 token for testing') 83 | parser.add_option('--generate_oauth2_string', 84 | action='store_true', 85 | dest='generate_oauth2_string', 86 | help='generates an initial client response string for ' 87 | 'OAuth2') 88 | parser.add_option('--client_id', 89 | default=None, 90 | help='Client ID of the application that is authenticating. ' 91 | 'See OAuth2 documentation for details.') 92 | parser.add_option('--client_secret', 93 | default=None, 94 | help='Client secret of the application that is ' 95 | 'authenticating. See OAuth2 documentation for ' 96 | 'details.') 97 | parser.add_option('--access_token', 98 | default=None, 99 | help='OAuth2 access token') 100 | parser.add_option('--refresh_token', 101 | default=None, 102 | help='OAuth2 refresh token') 103 | parser.add_option('--scope', 104 | default='https://mail.google.com/', 105 | help='scope for the access token. Multiple scopes can be ' 106 | 'listed separated by spaces with the whole argument ' 107 | 'quoted.') 108 | parser.add_option('--test_imap_authentication', 109 | action='store_true', 110 | dest='test_imap_authentication', 111 | help='attempts to authenticate to IMAP') 112 | parser.add_option('--test_smtp_authentication', 113 | action='store_true', 114 | dest='test_smtp_authentication', 115 | help='attempts to authenticate to SMTP') 116 | parser.add_option('--user', 117 | default=None, 118 | help='email address of user whose account is being ' 119 | 'accessed') 120 | parser.add_option('--quiet', 121 | action='store_true', 122 | default=False, 123 | dest='quiet', 124 | help='Omit verbose descriptions and only print ' 125 | 'machine-readable outputs.') 126 | return parser 127 | 128 | 129 | # The URL root for accessing Google Accounts. 130 | GOOGLE_ACCOUNTS_BASE_URL = 'https://accounts.google.com' 131 | 132 | 133 | # Hardcoded dummy redirect URI for non-web apps. 134 | REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' 135 | 136 | 137 | def AccountsUrl(command): 138 | """Generates the Google Accounts URL. 139 | 140 | Args: 141 | command: The command to execute. 142 | 143 | Returns: 144 | A URL for the given command. 145 | """ 146 | return '%s/%s' % (GOOGLE_ACCOUNTS_BASE_URL, command) 147 | 148 | 149 | def UrlEscape(text): 150 | # See OAUTH 5.1 for a definition of which characters need to be escaped. 151 | return six.moves.urllib.parse.quote(text, safe='~-._') 152 | 153 | 154 | def UrlUnescape(text): 155 | # See OAUTH 5.1 for a definition of which characters need to be escaped. 156 | return six.moves.urllib.parse.unquote(text) 157 | 158 | 159 | def FormatUrlParams(params): 160 | """Formats parameters into a URL query string. 161 | 162 | Args: 163 | params: A key-value map. 164 | 165 | Returns: 166 | A URL query string version of the given parameters. 167 | """ 168 | param_fragments = [] 169 | for param in sorted(params.items(), key=lambda x: x[0]): 170 | param_fragments.append('%s=%s' % (param[0], UrlEscape(param[1]))) 171 | return '&'.join(param_fragments) 172 | 173 | 174 | def GeneratePermissionUrl(client_id, scope='https://mail.google.com/'): 175 | """Generates the URL for authorizing access. 176 | 177 | This uses the "OAuth2 for Installed Applications" flow described at 178 | https://developers.google.com/accounts/docs/OAuth2InstalledApp 179 | 180 | Args: 181 | client_id: Client ID obtained by registering your app. 182 | scope: scope for access token, e.g. 'https://mail.google.com' 183 | Returns: 184 | A URL that the user should visit in their browser. 185 | """ 186 | params = {} 187 | params['client_id'] = client_id 188 | params['redirect_uri'] = REDIRECT_URI 189 | params['scope'] = scope 190 | params['response_type'] = 'code' 191 | return '%s?%s' % (AccountsUrl('o/oauth2/auth'), 192 | FormatUrlParams(params)) 193 | 194 | 195 | def AuthorizeTokens(client_id, client_secret, authorization_code): 196 | """Obtains OAuth access token and refresh token. 197 | 198 | This uses the application portion of the "OAuth2 for Installed Applications" 199 | flow at https://developers.google.com/accounts/docs/OAuth2InstalledApp#handlingtheresponse 200 | 201 | Args: 202 | client_id: Client ID obtained by registering your app. 203 | client_secret: Client secret obtained by registering your app. 204 | authorization_code: code generated by Google Accounts after user grants 205 | permission. 206 | Returns: 207 | The decoded response from the Google Accounts server, as a dict. Expected 208 | fields include 'access_token', 'expires_in', and 'refresh_token'. 209 | """ 210 | params = {} 211 | params['client_id'] = client_id 212 | params['client_secret'] = client_secret 213 | params['code'] = authorization_code 214 | params['redirect_uri'] = REDIRECT_URI 215 | params['grant_type'] = 'authorization_code' 216 | request_url = AccountsUrl('o/oauth2/token') 217 | 218 | response = six.moves.urllib.request.urlopen( 219 | request_url, six.moves.urllib.parse.urlencode(params).encode('utf-8')).read() 220 | return json.loads(response) 221 | 222 | 223 | def RefreshToken(client_id, client_secret, refresh_token): 224 | """Obtains a new token given a refresh token. 225 | 226 | See https://developers.google.com/accounts/docs/OAuth2InstalledApp#refresh 227 | 228 | Args: 229 | client_id: Client ID obtained by registering your app. 230 | client_secret: Client secret obtained by registering your app. 231 | refresh_token: A previously-obtained refresh token. 232 | Returns: 233 | The decoded response from the Google Accounts server, as a dict. Expected 234 | fields include 'access_token', 'expires_in', and 'refresh_token'. 235 | """ 236 | params = {} 237 | params['client_id'] = client_id 238 | params['client_secret'] = client_secret 239 | params['refresh_token'] = refresh_token 240 | params['grant_type'] = 'refresh_token' 241 | request_url = AccountsUrl('o/oauth2/token') 242 | 243 | response = six.moves.urllib.request.urlopen( 244 | request_url, six.moves.urllib.parse.urlencode(params).encode('utf-8')).read() 245 | return json.loads(response) 246 | 247 | 248 | def GenerateOAuth2String(username, access_token, base64_encode=True): 249 | """Generates an IMAP OAuth2 authentication string. 250 | 251 | See https://developers.google.com/google-apps/gmail/oauth2_overview 252 | 253 | Args: 254 | username: the username (email address) of the account to authenticate 255 | access_token: An OAuth2 access token. 256 | base64_encode: Whether to base64-encode the output. 257 | 258 | Returns: 259 | The SASL argument for the OAuth2 mechanism. 260 | """ 261 | auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token) 262 | if base64_encode: 263 | auth_string = base64.b64encode(auth_string) 264 | return auth_string 265 | 266 | 267 | def TestImapAuthentication(user, auth_string): 268 | """Authenticates to IMAP with the given auth_string. 269 | 270 | Prints a debug trace of the attempted IMAP connection. 271 | 272 | Args: 273 | user: The Gmail username (full email address) 274 | auth_string: A valid OAuth2 string, as returned by GenerateOAuth2String. 275 | Must not be base64-encoded, since imaplib does its own base64-encoding. 276 | """ 277 | print() 278 | imap_conn = imaplib.IMAP4_SSL('imap.gmail.com') 279 | imap_conn.debug = 4 280 | imap_conn.authenticate('XOAUTH2', lambda x: auth_string) 281 | imap_conn.select('INBOX') 282 | 283 | 284 | def TestSmtpAuthentication(user, auth_string): 285 | """Authenticates to SMTP with the given auth_string. 286 | 287 | Args: 288 | user: The Gmail username (full email address) 289 | auth_string: A valid OAuth2 string, not base64-encoded, as returned by 290 | GenerateOAuth2String. 291 | """ 292 | print() 293 | smtp_conn = smtplib.SMTP('smtp.gmail.com', 587) 294 | smtp_conn.set_debuglevel(True) 295 | smtp_conn.ehlo('test') 296 | smtp_conn.starttls() 297 | smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string)) 298 | 299 | 300 | def RequireOptions(options, *args): 301 | missing = [arg for arg in args if getattr(options, arg) is None] 302 | if missing: 303 | print('Missing options: %s' % ' '.join(missing)) 304 | sys.exit(-1) 305 | 306 | 307 | def main(): 308 | argv = sys.argv 309 | options_parser = SetupOptionParser() 310 | (options, args) = options_parser.parse_args() 311 | if options.refresh_token: 312 | RequireOptions(options, 'client_id', 'client_secret') 313 | response = RefreshToken(options.client_id, options.client_secret, 314 | options.refresh_token) 315 | if options.quiet: 316 | print(response['access_token']) 317 | else: 318 | print('Access Token: %s' % response['access_token']) 319 | print('Access Token Expiration Seconds: %s' % response['expires_in']) 320 | elif options.generate_oauth2_string: 321 | RequireOptions(options, 'user', 'access_token') 322 | oauth2_string = GenerateOAuth2String(options.user, options.access_token) 323 | if options.quiet: 324 | print(oauth2_string) 325 | else: 326 | print('OAuth2 argument:\n' + oauth2_string) 327 | elif options.generate_oauth2_token: 328 | RequireOptions(options, 'client_id', 'client_secret') 329 | print('To authorize token, visit this url and follow the directions:') 330 | print(' %s' % GeneratePermissionUrl(options.client_id, options.scope)) 331 | authorization_code = six.moves.input('Enter verification code: ') 332 | response = AuthorizeTokens(options.client_id, options.client_secret, 333 | authorization_code) 334 | print('Refresh Token: %s' % response['refresh_token']) 335 | print('Access Token: %s' % response['access_token']) 336 | print('Access Token Expiration Seconds: %s' % response['expires_in']) 337 | elif options.test_imap_authentication: 338 | RequireOptions(options, 'user', 'access_token') 339 | TestImapAuthentication(options.user, 340 | GenerateOAuth2String(options.user, options.access_token, 341 | base64_encode=False)) 342 | elif options.test_smtp_authentication: 343 | RequireOptions(options, 'user', 'access_token') 344 | TestSmtpAuthentication(options.user, 345 | GenerateOAuth2String(options.user, options.access_token, 346 | base64_encode=False)) 347 | else: 348 | options_parser.print_help() 349 | print('Nothing to do, exiting.') 350 | return 351 | 352 | 353 | if __name__ == '__main__': 354 | main() -------------------------------------------------------------------------------- /gmailapi_backend/mail.py: -------------------------------------------------------------------------------- 1 | """ 2 | Email backend that uses the GMail API via OAuth2 authentication. 3 | """ 4 | import base64 5 | import logging 6 | 7 | from django.conf import settings 8 | from django.core.mail.backends.base import BaseEmailBackend 9 | 10 | import google.oauth2.credentials 11 | import googleapiclient.discovery 12 | 13 | logger = logging.getLogger(__name__) 14 | 15 | 16 | class GmailBackend(BaseEmailBackend): 17 | def __init__(self, client_id=None, client_secret=None, refresh_token=None, 18 | user_id=None, fail_silently=False, **kwargs): 19 | super().__init__(fail_silently=fail_silently, **kwargs) 20 | self.client_id = client_id or settings.GMAIL_API_CLIENT_ID 21 | self.client_secret = client_secret or settings.GMAIL_API_CLIENT_SECRET 22 | self.refresh_token = refresh_token or settings.GMAIL_API_REFRESH_TOKEN 23 | if hasattr(settings, 'GMAIL_API_USER_ID'): 24 | self.user_id = user_id or settings.GMAIL_API_USER_ID 25 | else: 26 | self.user_id = user_id or 'me' 27 | 28 | credentials = google.oauth2.credentials.Credentials( 29 | 'token', 30 | refresh_token=self.refresh_token, 31 | token_uri='https://accounts.google.com/o/oauth2/token', 32 | client_id=self.client_id, 33 | client_secret=self.client_secret 34 | ) 35 | self.service = googleapiclient.discovery.build('gmail', 'v1', credentials=credentials, cache_discovery=False) 36 | 37 | def send_message(self, email_message): 38 | if not email_message.recipients(): 39 | return False 40 | message = email_message.message() 41 | if email_message.bcc: 42 | email_message._set_list_header_if_not_empty(message, 'Bcc', email_message.bcc) 43 | raw_message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()} 44 | return self.service.users().messages().send(userId=self.user_id, body=raw_message) 45 | 46 | def send_messages(self, email_messages): 47 | """Send all messages using BatchHttpRequest""" 48 | if not email_messages: 49 | return 0 50 | msg_count = 0 51 | last_exception = None 52 | 53 | def send_callback(r_id, response, exception): 54 | nonlocal msg_count, last_exception 55 | if exception is not None: 56 | logger.exception('An error occurred sending the message via GMail API: %s', exception) 57 | last_exception = exception 58 | else: 59 | msg_count += 1 60 | 61 | batch = self.service.new_batch_http_request(send_callback) 62 | for message in email_messages: 63 | batch.add(self.send_message(message)) 64 | batch.execute() 65 | if not self.fail_silently and last_exception: 66 | raise last_exception 67 | return msg_count 68 | -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | testpaths = tests 3 | python_files = tests/*.py 4 | norecursedirs = venv, manual 5 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | appdirs 2 | docopt 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import re 2 | from setuptools import setup, find_packages 3 | 4 | import sys 5 | if sys.version_info < (3, 5): 6 | raise 'must use Python version 3.5 or higher' 7 | 8 | with open('./gmailapi_backend/__init__.py', 'r') as f: 9 | MATCH_EXPR = "__version__[^'\"]+(['\"])([^'\"]+)" 10 | VERSION = re.search(MATCH_EXPR, f.read()).group(2).strip() 11 | 12 | 13 | setup( 14 | name='django-gmailapi-backend', 15 | version=VERSION, 16 | packages=find_packages(), 17 | author="Michele Dolfi", 18 | author_email="michele.dolfi@gmail.com", 19 | license="Apache License 2.0", 20 | entry_points={ 21 | 'console_scripts': [ 22 | 'gmail_oauth2 = gmailapi_backend.bin.gmail_oauth2:main', 23 | ] 24 | }, 25 | install_requires=[ 26 | 'google-api-python-client~=2.0', 27 | 'google-auth>=1.16.0,<3.0.0dev', 28 | ], 29 | url="https://github.com/dolfim/django-gmailapi-backend", 30 | long_description_content_type='text/markdown', 31 | long_description=open('README.md').read(), 32 | description='Email backend for Django which sends email via the Gmail API', 33 | classifiers=[ 34 | 'Intended Audience :: Developers', 35 | 'License :: OSI Approved :: Apache Software License', 36 | 'Operating System :: MacOS :: MacOS X', 37 | 'Operating System :: Microsoft :: Windows', 38 | 'Operating System :: POSIX', 39 | 'Programming Language :: Python', 40 | 'Programming Language :: Python :: 3', 41 | 'Programming Language :: Python :: 3.5', 42 | 'Programming Language :: Python :: 3.6', 43 | 'Programming Language :: Python :: 3.7', 44 | 'Programming Language :: Python :: 3.8', 45 | 'Framework :: Django', 46 | 'Topic :: Communications :: Email', 47 | 'Development Status :: 4 - Beta' 48 | ], 49 | ) 50 | --------------------------------------------------------------------------------