|
| 1 | +# Copyright 2016 Google Inc. All Rights Reserved. |
| 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 | +# [START app] |
| 16 | +import logging |
| 17 | +import os |
| 18 | + |
| 19 | +from flask import Flask, render_template, request |
| 20 | +# [start config] |
| 21 | +import mailjet_rest |
| 22 | +import requests_toolbelt.adapters.appengine |
| 23 | + |
| 24 | +# Use the App Engine requests adapter to allow the requests library to be |
| 25 | +# used on App Engine. |
| 26 | +requests_toolbelt.adapters.appengine.monkeypatch() |
| 27 | + |
| 28 | +MAILJET_API_KEY = os.environ['MAILJET_API_KEY'] |
| 29 | +MAILJET_API_SECRET = os.environ['MAILJET_API_SECRET'] |
| 30 | +MAILJET_SENDER = os.environ['MAILJET_SENDER'] |
| 31 | +# [END config] |
| 32 | + |
| 33 | +app = Flask(__name__) |
| 34 | + |
| 35 | + |
| 36 | +# [START send_message] |
| 37 | +def send_message(to): |
| 38 | + client = mailjet_rest.Client( |
| 39 | + auth=(MAILJET_API_KEY, MAILJET_API_SECRET)) |
| 40 | + |
| 41 | + data = { |
| 42 | + 'FromEmail': MAILJET_SENDER, |
| 43 | + 'FromName': 'App Engine Flex Mailjet Sample', |
| 44 | + 'Subject': 'Example email.', |
| 45 | + 'Text-part': 'This is an example email.', |
| 46 | + 'Html-part': 'This is an <i>example</i> email.', |
| 47 | + 'Recipients': [{'Email': to}] |
| 48 | + } |
| 49 | + |
| 50 | + result = client.send.create(data=data) |
| 51 | + |
| 52 | + return result.json() |
| 53 | +# [END send_message] |
| 54 | + |
| 55 | + |
| 56 | +@app.route('/') |
| 57 | +def index(): |
| 58 | + return render_template('index.html') |
| 59 | + |
| 60 | + |
| 61 | +@app.route('/send/email', methods=['POST']) |
| 62 | +def send_email(): |
| 63 | + to = request.form.get('to') |
| 64 | + |
| 65 | + result = send_message(to) |
| 66 | + |
| 67 | + return 'Email sent, response: <pre>{}</pre>'.format(result) |
| 68 | + |
| 69 | + |
| 70 | +@app.errorhandler(500) |
| 71 | +def server_error(e): |
| 72 | + logging.exception('An error ocurred during a request.') |
| 73 | + return """ |
| 74 | + An internal error occurred: <pre>{}</pre> |
| 75 | + See logs for full stacktrace. |
| 76 | + """.format(e), 500 |
| 77 | +# [END app] |
0 commit comments