├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── img ├── sendgrid-http.png └── sendgrid-pubsub.png ├── sendgrid-http ├── CONTRIBUTING.md ├── README.md ├── main.py └── requirements.txt └── sendgrid-pubsub ├── CONTRIBUTING.md ├── README.md ├── main.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | **/.DS_Store 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement (CLA). You (or your employer) retain the copyright to your 10 | contribution; this simply gives us permission to use and redistribute your 11 | contributions as part of the project. Head over to 12 | to see your current agreements on file or 13 | to sign a new one. 14 | 15 | You generally only need to submit a CLA once, so if you've already submitted one 16 | (even if it was for a different project), you probably don't need to do it 17 | again. 18 | 19 | ## Code Reviews 20 | 21 | All submissions, including submissions by project members, require review. We 22 | use GitHub pull requests for this purpose. Consult 23 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 24 | information on using pull requests. 25 | 26 | ## Community Guidelines 27 | 28 | This project follows 29 | [Google's Open Source Community Guidelines](https://opensource.google/conduct/). 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Using Secret Manager and Cloud Functions to call SendGrid 2 | 3 | ## Introduction 4 | 5 | One of the needs that arises in cloud infrastructures is the ability to send email messages about the status of systems, error messages, or various findings. 6 | Google Cloud offers a [list of suggestions](https://cloud.google.com/compute/docs/tutorials/sending-mail) one of which is SendGrid. 7 | The purpose of this repository is to show how to use Google Cloud Functions to call the SendGrid API. 8 | 9 | You can add the SendGrid API to your Google Cloud environment using the [Google Cloud Marketplace](https://cloud.google.com/marketplace). 10 | The SendGrid API Marketplace page contains sample code in several languages but there are some additional matters to consider beyond calling the SendGrid API. 11 | For exmaple: 12 | 13 | 1. How does one protect the SendGrid API key? 14 | 2. How can we route messages to SendGrid via Cloud Pub/Sub and support a protected API key? 15 | 3. Can we address all of these items in a modular manner to promote reusability? 16 | 17 | We are going to look at how we can address these concerns using Google [Cloud Functions](https://cloud.google.com/functions) and [Secret Manager](https://cloud.google.com/secret-manager). 18 | Cloud Functions is a serverless-compute capability that executes code based on an event such as a publication to Cloud Pub/Sub or an HTTP call. 19 | Secret Manager provides the ability to protected sensitive value such as API keys and offers encryption along with version control. 20 | The two Cloud Functions provided in this repository handle the work of fetching and decoding the SendGrid API key from Secret Manager and then calling SendGrid API. 21 | 22 | ## Use Cases 23 | 24 | As mentioned above, there are two Cloud Functions in this repository that address two different use cases. 25 | 26 | 1. The sendgrid_pubsub Cloud Function is used to call SendGrid from a Cloud Pub/Sub topic. 27 | You subscribe the Cloud Function to the topic. 28 | When a publisher posts a messsage to the topic, Cloud Pub/Sub notifies the Cloud Function that a message is ready and the Cloud Function then fetches the API key from Secret Manager and then posts the message to SendGrid. Here is a diagram of this use case. 29 | 30 | ![PubSub use case image](img/sendgrid-pubsub.png) 31 | 32 | 2. The sendgrid_http Cloud Function is used to call SendGrid via an HTTP call. When the Cloud Function is called it fetches the API key from Secret Manager and then posts the message to SendGrid. Here is a diagram of this use case. 33 | 34 | ![HTTP use case image](img/sendgrid-http.png) 35 | 36 | ## Prerequisites 37 | 38 | You should be familiar with the implementation of the Google Cloud Console, GCP projects, IAM, Cloud Functions, and Secret Manager. 39 | A knowledge of Cloud Logging will be helpful in identifying any errors that may arise during the deployments. 40 | 41 | 42 | ## Network and security considerations 43 | 44 | 1. The service account you use for these Cloud Functions does not need any project level IAM permissions. You must, however, grant the service account Secret Manager Accessor permission to the secret containing the Sendgrid API key. You can do this within the Secret Manager console. 45 | 46 | 2. Limit the flow of traffic to the function and accept the default of requiring authentication. While you may choose to temporarily relax these constraints for testing purposes, enabling unauthenticated access and allowing all internet traffic increases the risk level substantially and is not recommended. 47 | 48 | ## Implementation guide 49 | 50 | The procedures listed below are not step-by-step instructions but rather a guide to what must be done. 51 | You should be famiiar with the Google Cloud console and have a general understand of the GCP services involved which include (but are not limited to) Cloud Functions, IAM, and Secret Function. 52 | 53 | 1. Get a SendGrid API key. You can do this by using the Google Cloud Marketplace. Look for the SendGrid Email API product. Make sure you are aware of any pricing considerations before buying SendGrid from the Marketplace. As of the time this repository was created, there was a free tier but please check. You will also need to aunthenticate your sender address or a domain. 54 | 55 | 2. Create a Secret Manager secret for the API Key. The default secret name in the code is SENDGRID_API_KEY. 56 | 3. Create an IAM service account for the Cloud Function. It does not need any project-level IAM permissions. 57 | 4. In the Secret Manager console, select the Secret, go to the Permissions tab and grant the service account the Secret Manager Accessor role. You are attaching the permission to the secret resource. You will not see this permmission in the project-level IAM settings. 58 | 5. For the Cloud Pub/Sub use case, create a Cloud Pub/Sub topic. 59 | 6. Here are the steps for deploying the Cloud Functions. 60 | 1. Either clone this repository into Cloud Source Repositories or you can create a connected repository that points to this GitHub repository. 61 | 2. When you deploy each Cloud Function, make sure you set the folder path to the correct folder name so the deployment picks up the correct code. The function names and subdirectory names within the repository appear below. Note that the function names use underscores ("_") while the subdirectory names use hyphens ("-"). 62 | 63 | | Entry Point | Subdirectory | Description | Trigger Type | 64 | |-|-|-|-| 65 | |sendgrid_pubsub|sendgrid-pubsub|Consumes requests from a Cloud Pub/Sub topic|Cloud Pub/Sub| 66 | |sendgrid_http|sendgrid-http|Provides an HTTP endpoint for submitting email requests|HTTP| 67 | 68 | 3. Select the trigger type associated with the function you are deploying. 69 | 4. These functions were tested against the Python 3.9 framework. Earlier versions may not work. 70 | 5. Do not assign any environment variables or secrets to the Cloud Function. The function will query GCP for the values it needs. 71 | 6. Use the IAM service account you created earlier. 72 | 7. For the Cloud Pub/Sub use case, specify the Cloud Pub/Sub topic that you created earlier. 73 | 8. Study the main.py file in the function to see how errors are handled. You may wish to change the error reporting. 74 | 75 | ## Testing the cloud functions 76 | 77 | ### The Cloud Pub/Sub use case 78 | 79 | The sendgrid_pubsub function accepts a message containing a JSON string with the arguments listed in the table below. 80 | 81 | | JSON Key | Value | 82 | |---------------|-------| 83 | |project_id | This is the GCP project ID in which the secret containing the API key resides. This needs to be passed since the newest Cloud Function Python framework does not pass over an environment variable with the project ID like the older versions.| 84 | |secret|This is the name of the Secret Manager secret that holds the Sendgrid API key. The default secret name is SENDGRID_API_KEY.| 85 | |secret_version|This is the version number of the secret. The default is "latest" which means the most recent version of the secret.| 86 | |from_address|This is the sender's email address. You must validate this within Sendgrid.| 87 | |to_address|This is the recipient's email address.| 88 | |subject|This is the subject of the message. The default valueis an empty subject.| 89 | |plain_text_content|The plaintext (not HTML) message. The default is an empty message.| 90 | 91 | You can test the Cloud Function using the gcloud command similar to the example below. 92 | 93 | gcloud pubsub topics publish YOUR_TOPIC_NAME --message=' 94 | { 95 | "project_id" : "YOUR_PROJECT_ID", 96 | "secret" : "SENDGRID_API_KEY", 97 | "secret_version" : "latest", 98 | "from_address" : "from@example.com", 99 | "to_address" : "to@example.com", 100 | "subject" : "This is a Test Message", 101 | "plain_text_content" : "Hello world!" 102 | }' 103 | 104 | ### The HTTP use case 105 | 106 | The sendgrid_http function accepts the arguments listed in the table below. 107 | 108 | | JSON Key | Value | 109 | |---------------|-------| 110 | |project_id | This is the GCP project ID in which the secret containing the API key resides. This needs to be passed since the newest Cloud Function Python framework does not pass over an environment variable with the project ID like the older versions.| 111 | |secret|This is the name of the Secret Manager secret that holds the Sendgrid API key. The default secret name is SENDGRID_API_KEY.| 112 | |secret_version|This is the version number of the secret. The default is "latest" which means the most recent version of the secret.| 113 | |from_address|This is the sender's email address. You must validate this within Sendgrid.| 114 | |to_address|This is the recipient's email address.| 115 | |subject|This is the subject of the message. The default valueis an empty subject.| 116 | |plain_text_content|The plaintext (not HTML) message. The default is an empty message.| 117 | 118 | Use the test option in the Cloud Functions console with the following JSON string to test the function. 119 | 120 | { 121 | "project_id" : "YOUR_PROJECT_ID", 122 | "secret" : "SENDGRID_API_KEY", 123 | "secret_version" : "latest", 124 | "from_address" : "from@example.com", 125 | "to_address" : "to@example.com", 126 | "subject" : "This is a Test Message", 127 | "plain_text_content" : "Hello world!" 128 | } 129 | 130 | 131 | ## Suggestions for enhancements? 132 | 133 | All suggestions are welcome! Please see the [CONTRIBUTING.md](CONTRIBUTING.md) file for more information. 134 | -------------------------------------------------------------------------------- /img/sendgrid-http.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/secret-manager-with-sendgrid/04f2b228b501a1e1f5e1b85a98a59e253b05ebab/img/sendgrid-http.png -------------------------------------------------------------------------------- /img/sendgrid-pubsub.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/google/secret-manager-with-sendgrid/04f2b228b501a1e1f5e1b85a98a59e253b05ebab/img/sendgrid-pubsub.png -------------------------------------------------------------------------------- /sendgrid-http/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement (CLA). You (or your employer) retain the copyright to your 10 | contribution; this simply gives us permission to use and redistribute your 11 | contributions as part of the project. Head over to 12 | to see your current agreements on file or 13 | to sign a new one. 14 | 15 | You generally only need to submit a CLA once, so if you've already submitted one 16 | (even if it was for a different project), you probably don't need to do it 17 | again. 18 | 19 | ## Code Reviews 20 | 21 | All submissions, including submissions by project members, require review. We 22 | use GitHub pull requests for this purpose. Consult 23 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 24 | information on using pull requests. 25 | 26 | ## Community Guidelines 27 | 28 | This project follows 29 | [Google's Open Source Community Guidelines](https://opensource.google/conduct/). 30 | -------------------------------------------------------------------------------- /sendgrid-http/README.md: -------------------------------------------------------------------------------- 1 | # sendgrid_http 2 | 3 | This directory is a Google Cloud Platform ("GCP") Cloud Function triggered by HTTP written in Python that invokes Sendgrid to send an email message. Please consult the README.md in the parent directory for more information. 4 | -------------------------------------------------------------------------------- /sendgrid-http/main.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # sendgrid_http - An HTTP Google Cloud Function for calling Sendgrid 16 | # 17 | # Please see the README.md file in the parent directory for information 18 | # about deploying the function. 19 | # 20 | # Responds to any HTTP request. 21 | # 22 | # Args: 23 | # request (flask.Request): HTTP request object. 24 | # 25 | # Returns: 26 | # The response text or any set of values that can be turned into a respons object using 27 | # `make_response `. 28 | 29 | def sendgrid_http(request): 30 | import logging 31 | import os 32 | import sendgrid 33 | from flask import abort, Response 34 | from http import HTTPStatus 35 | from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent 36 | 37 | from google.cloud import secretmanager 38 | 39 | request_json = request.get_json(silent=True) 40 | request_args = request.args 41 | 42 | # The Flask framework is used for Python Cloud Functions. 43 | # If there is no JSON string and no args, something is wrong. 44 | 45 | if not (request_json or request_args): 46 | error_message = 'send_mail: no arguments or request passed to Flask framework' 47 | logging.error(error_message) 48 | return abort(HTTPStatus.BAD_REQUEST.value, error_message) 49 | 50 | # Fetch the GCP project ID from the request JSON or args with the key 51 | # name "project_id." If it is not present, raise an exception since 52 | # we cannot proceed further without a project ID. 53 | 54 | if request_json and 'project_id' in request_json: 55 | project_id = request_json['project_id'] 56 | elif request_args and 'project_id' in request_args: 57 | project_id = request_args['project_id'] 58 | else: 59 | error_message = 'send_mail: project_id not found in request json or arguments' 60 | logging.error(error_message) 61 | return abort(HTTPStatus.BAD_REQUEST.value, error_message) 62 | 63 | # Fetch the "from address" from the request JSON or args with the key 64 | # name "from_address." If it is not present, raise an exception since 65 | # we cannot proceed further without a from_address. 66 | 67 | if request_json and 'from_address' in request_json: 68 | from_address = request_json['from_address'] 69 | elif request_args and 'from_address' in request_args: 70 | from_address = request_args['from_address'] 71 | else: 72 | error_message = 'send_mail: from_address not found in request json or arguments' 73 | logging.error(error_message) 74 | return abort(HTTPStatus.BAD_REQUEST.value, error_message) 75 | 76 | # Fetch the "to address" from the request JSON or args with the key 77 | # name "to_address." If it is not present, raise an exception since 78 | # we cannot proceed further without a to_address. 79 | 80 | if request_json and 'to_address' in request_json: 81 | to_address = request_json['to_address'] 82 | elif request_args and 'to_address' in request_args: 83 | to_address = request_args['to_address'] 84 | else: 85 | error_message = 'send_mail: to_address not found in request json or arguments' 86 | logging.error(error_message) 87 | return abort(HTTPStatus.BAD_REQUEST.value, error_message) 88 | 89 | # Fetch the message subject from the request JSON or args with the key 90 | # name "subject." If it is not present, assume the value of '' (a zero 91 | # length string). 92 | 93 | if request_json and 'subject' in request_json: 94 | subject = request_json['subject'] 95 | elif request_args and 'subject' in request_args: 96 | subject = request_args['subject'] 97 | else: 98 | subject = '' 99 | 100 | # Fetch the message body from the request JSON or args with the key 101 | # name "content." If it is not present, assume the value of '' (a zero 102 | # length string). 103 | 104 | if request_json and 'plain_text_content' in request_json: 105 | plain_text_content = request_json['plain_text_content'] 106 | elif request_args and 'plain_text_content' in request_args: 107 | plain_text_content = request_args['plain_text_content'] 108 | else: 109 | plain_text_content = '' 110 | 111 | # Fetch the name (not the value) of the secret from the request JSON 112 | # or args with the key name "secret." If it is not present, assume the 113 | # value of "SENDGRID_API_KEY." 114 | 115 | if request_json and 'secret' in request_json: 116 | secret = request_json['secret'] 117 | elif request_args and 'secret' in request_args: 118 | secret = request_args['secret'] 119 | else: 120 | secret = 'SENDGRID_API_KEY' 121 | 122 | # Fetch the version of the secret from the request JSON or args 123 | # with the key name "secret_version." If it is not present, 124 | # assume the value of "latest." 125 | 126 | if request_json and 'secret_version' in request_json: 127 | secret_version = request_json['secret_version'] 128 | elif request_args and 'secret_version' in request_args: 129 | secret_version = request_args['secret_version'] 130 | else: 131 | secret_version = 'latest' 132 | 133 | # Create the full secret name and retrieve the secret. 134 | # Raise an exception if the retrieval fails. 135 | 136 | client = secretmanager.SecretManagerServiceClient() 137 | full_secret_name = client.secret_version_path(project_id, secret, secret_version) 138 | 139 | try: 140 | response = client.access_secret_version(name=full_secret_name) 141 | except Exception as e: 142 | error_message = 'send_mail: unable to retrieve secret ' + full_secret_name 143 | logging.error(error_message) 144 | return abort(HTTPStatus.BAD_REQUEST.value, error_message) 145 | 146 | # Decode the encrypted secret and get the Sendgrid API key. 147 | 148 | sendgrid_api_key = response.payload.data.decode('UTF-8') 149 | 150 | # Use the Sendgrid API to send the message. 151 | 152 | sg = sendgrid.SendGridAPIClient(api_key = sendgrid_api_key) 153 | from_address = From(from_address) 154 | to_address = To(to_address) 155 | subject = Subject(subject) 156 | plain_text_content = PlainTextContent(plain_text_content) 157 | sendgrid_mail = Mail( 158 | from_email=from_address, 159 | to_emails=to_address, 160 | subject=subject, 161 | plain_text_content=plain_text_content) 162 | response = sg.send(message=sendgrid_mail) 163 | 164 | # Use the Sendgrid return status for the the Cloud Function status code. 165 | 166 | status_code = Response(response=response.body, status=response.status_code) 167 | return status_code 168 | -------------------------------------------------------------------------------- /sendgrid-http/requirements.txt: -------------------------------------------------------------------------------- 1 | google-cloud-secret-manager 2 | sendgrid 3 | -------------------------------------------------------------------------------- /sendgrid-pubsub/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to Contribute 2 | 3 | We'd love to accept your patches and contributions to this project. There are 4 | just a few small guidelines you need to follow. 5 | 6 | ## Contributor License Agreement 7 | 8 | Contributions to this project must be accompanied by a Contributor License 9 | Agreement (CLA). You (or your employer) retain the copyright to your 10 | contribution; this simply gives us permission to use and redistribute your 11 | contributions as part of the project. Head over to 12 | to see your current agreements on file or 13 | to sign a new one. 14 | 15 | You generally only need to submit a CLA once, so if you've already submitted one 16 | (even if it was for a different project), you probably don't need to do it 17 | again. 18 | 19 | ## Code Reviews 20 | 21 | All submissions, including submissions by project members, require review. We 22 | use GitHub pull requests for this purpose. Consult 23 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 24 | information on using pull requests. 25 | 26 | ## Community Guidelines 27 | 28 | This project follows 29 | [Google's Open Source Community Guidelines](https://opensource.google/conduct/). 30 | -------------------------------------------------------------------------------- /sendgrid-pubsub/README.md: -------------------------------------------------------------------------------- 1 | # sendgrid_pubsub 2 | 3 | This directory is a Google Cloud Platform ("GCP") Cloud Function triggered by Cloud Pub/Sub written in Python that invokes Sendgrid to send an email message. Please consult the README.md file in the parent directory for more information. 4 | -------------------------------------------------------------------------------- /sendgrid-pubsub/main.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Google LLC 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | # sengrid_pubsub - A Pub/Sub Google Cloud Function for calling Sendgrid 16 | # 17 | # Function arguments 18 | # 19 | # event (dict): 20 | # The dictionary with data specific to this type of event. 21 | # The `@type` field maps to 22 | # 23 | # `type.googleapis.com/google.pubsub.v1.PubsubMessage`. 24 | # 25 | # The `data` field maps to the PubsubMessage data in a base64-encoded string. 26 | # The `attributes` field maps to the PubsubMessage attributes if any is 27 | # present. 28 | # 29 | # context (google.cloud.functions.Context): 30 | # 31 | # Metadata of triggering eveng including `event_id` which maps to the 32 | # PubsubMessage messageId, `timestamp` which maps to the PubsubMessage 33 | # publishTime, `event_type` which maps to`google.pubsub.topic.publish`, 34 | # and `resource` which is a dictionary that describes the service API 35 | # endpoint pubsub.googleapis.com, the triggering topic's name, and 36 | # the triggering event type 37 | # `type.googleapis.com/google.pubsub.v1.PubsubMessage`. 38 | 39 | def sendgrid_pubsub(event, context): 40 | import base64 41 | import json 42 | import logging 43 | import sendgrid 44 | from flask import abort, Response 45 | from http import HTTPStatus 46 | from sendgrid.helpers.mail import Mail, From, To, Subject, PlainTextContent 47 | 48 | from google.cloud import secretmanager 49 | 50 | if 'data' not in event: 51 | error_message = 'send_mail: no data passed to Flask framework event' 52 | logging.error(error_message) 53 | return abort(HTTPStatus.BAD_REQUEST.value, error_message) 54 | 55 | try: 56 | event_data_json = json.loads(base64.b64decode(event['data']).decode('utf-8')) 57 | except Exception as e: 58 | error_message = 'send_mail: data does not contain a valid JSON string' 59 | logging.error(error_message) 60 | return abort(HTTPStatus.BAD_REQUEST.value, error_message) 61 | 62 | # Fetch the GCP project ID from the request JSON with the key 63 | # name "project_id." If it is not present, raise an exception since 64 | # we cannot proceed further without a project ID. 65 | 66 | if 'project_id' in event_data_json: 67 | project_id = event_data_json['project_id'] 68 | else: 69 | error_message = 'send_mail: project_id not found in request json or arguments' 70 | logging.error(error_message) 71 | return abort(HTTPStatus.BAD_REQUEST.value, error_message) 72 | 73 | # Fetch the "from address" from the request JSON with the key 74 | # name "from_address." If it is not present, raise an exception since 75 | # we cannot proceed further without a from_address. 76 | 77 | if 'from_address' in event_data_json: 78 | from_address = event_data_json['from_address'] 79 | else: 80 | error_message = 'send_mail: from_address not found in request json or arguments' 81 | logging.error(error_message) 82 | return abort(HTTPStatus.BAD_REQUEST.value, error_message) 83 | 84 | # Fetch the "to address" from the request JSON with the key 85 | # name "to_address." If it is not present, raise an exception since 86 | # we cannot proceed further without a to_address. 87 | 88 | if 'to_address' in event_data_json: 89 | to_address = event_data_json['to_address'] 90 | else: 91 | error_message = 'send_mail: to_address not found in request json or arguments' 92 | logging.error(error_message) 93 | return abort(HTTPStatus.BAD_REQUEST.value, error_message) 94 | 95 | # Fetch the message subject from the request JSON with the key 96 | # name "subject." If it is not present, assume the value of '' (a zero 97 | # length string). 98 | 99 | if 'subject' in event_data_json: 100 | subject = event_data_json['subject'] 101 | else: 102 | subject = '' 103 | 104 | # Fetch the message body from the request JSON with the key 105 | # name "content." If it is not present, assume the value of '' (a zero 106 | # length string). 107 | 108 | if 'plain_text_content' in event_data_json: 109 | plain_text_content = event_data_json['plain_text_content'] 110 | else: 111 | plain_text_content = '' 112 | 113 | # Fetch the name (not the value) of the secret from the request JSON 114 | # with the key name "secret." If it is not present, assume the 115 | # value of "SENDGRID_API_KEY." 116 | 117 | if 'secret' in event_data_json: 118 | secret = event_data_json['secret'] 119 | else: 120 | secret = 'SENDGRID_API_KEY' 121 | 122 | # Fetch the version of the secret from the request JSON 123 | # with the key name "secret_version." If it is not present, 124 | # assume the value of "latest." 125 | 126 | if 'secret_version' in event_data_json: 127 | secret_version = event_data_json['secret_version'] 128 | else: 129 | secret_version = 'latest' 130 | 131 | # Create the full secret name and retrieve the secret. 132 | # Raise an exception if the retrieval fails. 133 | 134 | client = secretmanager.SecretManagerServiceClient() 135 | full_secret_name = client.secret_version_path(project_id, secret, secret_version) 136 | 137 | try: 138 | response = client.access_secret_version(name=full_secret_name) 139 | except Exception as e: 140 | error_message = 'send_mail: unable to retrieve secret ' + full_secret_name 141 | logging.error(error_message) 142 | return abort(HTTPStatus.BAD_REQUEST.value, error_message) 143 | 144 | # Decode the encrypted secret and get the Sendgrid API key. 145 | 146 | sendgrid_api_key = response.payload.data.decode('UTF-8') 147 | 148 | # Use the Sendgrid API to send the message. 149 | 150 | sg = sendgrid.SendGridAPIClient(api_key = sendgrid_api_key) 151 | from_address = From(from_address) 152 | to_address = To(to_address) 153 | subject = Subject(subject) 154 | plain_text_content = PlainTextContent(plain_text_content) 155 | sendgrid_mail = Mail( 156 | from_email=from_address, 157 | to_emails=to_address, 158 | subject=subject, 159 | plain_text_content=plain_text_content) 160 | response = sg.send(message=sendgrid_mail) 161 | 162 | # Use the Sendgrid return status for the the Cloud Function status code. 163 | 164 | status_code = Response(response=response.body, status=response.status_code) 165 | return status_code 166 | -------------------------------------------------------------------------------- /sendgrid-pubsub/requirements.txt: -------------------------------------------------------------------------------- 1 | google-cloud-secret-manager 2 | sendgrid 3 | pytest 4 | --------------------------------------------------------------------------------