|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2016 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 | +import sendgrid |
| 18 | +import webapp2 |
| 19 | + |
| 20 | +# make a secure connection to SendGrid |
| 21 | +SENDGRID_API_KEY = 'your-sendgrid-api-key' |
| 22 | +SENDGRID_DOMAIN = 'your-sendgrid-domain' |
| 23 | + |
| 24 | +sg = sendgrid.SendGridClient(SENDGRID_API_KEY) |
| 25 | + |
| 26 | + |
| 27 | +def send_simple_message(recipient): |
| 28 | + message = sendgrid.Mail() |
| 29 | + message.set_subject('message subject') |
| 30 | + message.set_html('<strong>HTML message body</strong>') |
| 31 | + message.set_text('plaintext message body') |
| 32 | + message.set_from('from: Example Sender <mailgun@{}>'.format( |
| 33 | + SENDGRID_DOMAIN)) |
| 34 | + message.set_from('App Engine App <sendgrid@{}>'.format(SENDGRID_DOMAIN)) |
| 35 | + message.add_to(recipient) |
| 36 | + status, msg = sg.send(message) |
| 37 | + return (status, msg) |
| 38 | + |
| 39 | + |
| 40 | +class MainPage(webapp2.RequestHandler): |
| 41 | + def get(self): |
| 42 | + self.response.content_type = 'text/html' |
| 43 | + self.response.write(""" |
| 44 | +<!doctype html> |
| 45 | +<html><body> |
| 46 | +<form action="/send" method="POST"> |
| 47 | +<input type="text" name="recipient" placeholder="Enter recipient email"> |
| 48 | +<input type="submit" name="submit" value="Send simple email"> |
| 49 | +</form> |
| 50 | +</body></html> |
| 51 | +""") |
| 52 | + |
| 53 | + |
| 54 | +class SendEmailHandler(webapp2.RequestHandler): |
| 55 | + def post(self): |
| 56 | + recipient = self.request.get('recipient') |
| 57 | + (status, msg) = send_simple_message(recipient) |
| 58 | + self.response.set_status(status) |
| 59 | + if status == 200: |
| 60 | + self.response.write(msg) |
| 61 | + |
| 62 | + |
| 63 | +app = webapp2.WSGIApplication([ |
| 64 | + ('/', MainPage), |
| 65 | + ('/send', SendEmailHandler) |
| 66 | +], debug=True) |
0 commit comments