Skip to content

Commit

Permalink
Adding mailjet samples for standard and flex (#318)
Browse files Browse the repository at this point in the history
Change-Id: I64b2fd1d4e1176e9fcbecf2f75592e78007e6a8a
  • Loading branch information
Jon Wayne Parrott committed May 3, 2016
1 parent ffc65cf commit 48a3be6
Show file tree
Hide file tree
Showing 17 changed files with 446 additions and 30 deletions.
1 change: 1 addition & 0 deletions appengine/mailjet/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
lib
11 changes: 11 additions & 0 deletions appengine/mailjet/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Python Mailjet email sample for Google App Engine Standard

This sample demonstrates how to use [Mailjet](https://www.mailgun.com) on [Google App Engine Standard](https://cloud.google.com/appengine/docs/).

## Setup

Before you can run or deploy the sample, you will need to do the following:

1. [Create a Mailjet Account](http://www.mailjet.com/google).

2. Configure your Mailjet settings in the environment variables section in ``app.yaml``.
14 changes: 14 additions & 0 deletions appengine/mailjet/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
runtime: python27
threadsafe: yes
api_version: 1

handlers:
- url: .*
script: main.app

# [START env_variables]
env_variables:
MAILJET_API_KEY: your-mailjet-api-key
MAILJET_API_SECRET: your-mailjet-api-secret
MAILJET_SENDER: your-mailjet-sender-address
# [END env_variables]
18 changes: 18 additions & 0 deletions appengine/mailjet/appengine_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Copyright 2016 Google Inc.
#
# 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.

from google.appengine.ext import vendor

# Add any libraries installed in the "lib" folder.
vendor.add('lib')
77 changes: 77 additions & 0 deletions appengine/mailjet/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.

# [START app]
import logging
import os

from flask import Flask, render_template, request
# [start config]
import mailjet_rest
import requests_toolbelt.adapters.appengine

# Use the App Engine requests adapter to allow the requests library to be
# used on App Engine.
requests_toolbelt.adapters.appengine.monkeypatch()

MAILJET_API_KEY = os.environ['MAILJET_API_KEY']
MAILJET_API_SECRET = os.environ['MAILJET_API_SECRET']
MAILJET_SENDER = os.environ['MAILJET_SENDER']
# [END config]

app = Flask(__name__)


# [START send_message]
def send_message(to):
client = mailjet_rest.Client(
auth=(MAILJET_API_KEY, MAILJET_API_SECRET))

data = {
'FromEmail': MAILJET_SENDER,
'FromName': 'App Engine Flex Mailjet Sample',
'Subject': 'Example email.',
'Text-part': 'This is an example email.',
'Html-part': 'This is an <i>example</i> email.',
'Recipients': [{'Email': to}]
}

result = client.send.create(data=data)

return result.json()
# [END send_message]


@app.route('/')
def index():
return render_template('index.html')


@app.route('/send/email', methods=['POST'])
def send_email():
to = request.form.get('to')

result = send_message(to)

return 'Email sent, response: <pre>{}</pre>'.format(result)


@app.errorhandler(500)
def server_error(e):
logging.exception('An error ocurred during a request.')
return """
An internal error occurred: <pre>{}</pre>
See logs for full stacktrace.
""".format(e), 500
# [END app]
53 changes: 53 additions & 0 deletions appengine/mailjet/main_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.

import re

import pytest
import responses


@pytest.fixture
def app(monkeypatch):
monkeypatch.setenv('MAILJET_API_KEY', 'apikey')
monkeypatch.setenv('MAILJET_API_SECRET', 'apisecret')
monkeypatch.setenv('MAILJET_SENDER', 'sender')

import main

main.app.testing = True
return main.app.test_client()


def test_index(app):
r = app.get('/')
assert r.status_code == 200


@responses.activate
def test_send_email(app):
responses.add(
responses.POST,
re.compile(r'.*'),
body='{"test": "message"}',
content_type='application/json')

r = app.post('/send/email', data={'to': 'user@example.com'})

assert r.status_code == 200
assert 'test' in r.data.decode('utf-8')

assert len(responses.calls) == 1
request_body = responses.calls[0].request.body
assert 'user@example.com' in request_body
4 changes: 4 additions & 0 deletions appengine/mailjet/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Flask==0.10.1
requests==2.10.0
requests-toolbelt==0.6.0
mailjet_rest==1.1.1
29 changes: 29 additions & 0 deletions appengine/mailjet/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{#
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.
#}
<!doctype html>
<html>
<head>
<title>Mailjet on Google App Engine</title>
</head>
<body>
<!-- [START form] -->
<form method="post" action="/send/email">
<input type="text" name="to" placeholder="Enter recipient email">
<input type="submit" name="submit" value="Send email">
</form>
<!-- [END form] -->
</body>
</html>
23 changes: 23 additions & 0 deletions managed_vms/mailjet/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Python Mailjet email sample for Google App Engine Flexible

This sample demonstrates how to use [Mailjet](https://www.mailgun.com) on [Google App Engine Flexible](https://cloud.google.com/appengine/docs/flexible/).

## Setup

Before you can run or deploy the sample, you will need to do the following:

1. [Create a Mailjet Account](http://www.mailjet.com/google).

2. Configure your Mailjet settings in the environment variables section in ``app.yaml``.

## Running locally

Refer to the [top-level README](../README.md) for instructions on running and deploying.

You can run the application locally and send emails from your local machine. You
will need to set environment variables before starting your application:

$ export MAILGUN_API_KEY=[your-mailgun-api-key]
$ export MAILGUN_API_SECRET=[your-mailgun-secret]
$ export MAILGUN_SENDER=[your-sender-address]
$ python main.py
13 changes: 13 additions & 0 deletions managed_vms/mailjet/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
runtime: python
vm: true
entrypoint: gunicorn -b :$PORT main:app

runtime_config:
python_version: 3

# [START env_variables]
env_variables:
MAILJET_API_KEY: your-mailjet-api-key
MAILJET_API_SECRET: your-mailjet-api-secret
MAILJET_SENDER: your-mailjet-sender-address
# [END env_variables]
78 changes: 78 additions & 0 deletions managed_vms/mailjet/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.

# [START app]
import logging
import os

from flask import Flask, render_template, request
# [start config]
import mailjet_rest

MAILJET_API_KEY = os.environ['MAILJET_API_KEY']
MAILJET_API_SECRET = os.environ['MAILJET_API_SECRET']
MAILJET_SENDER = os.environ['MAILJET_SENDER']
# [END config]

app = Flask(__name__)


# [START send_message]
def send_message(to):
client = mailjet_rest.Client(
auth=(MAILJET_API_KEY, MAILJET_API_SECRET))

data = {
'FromEmail': MAILJET_SENDER,
'FromName': 'App Engine Flex Mailjet Sample',
'Subject': 'Example email.',
'Text-part': 'This is an example email.',
'Html-part': 'This is an <i>example</i> email.',
'Recipients': [{'Email': to}]
}

result = client.send.create(data=data)

return result.json()
# [END send_message]


@app.route('/')
def index():
return render_template('index.html')


@app.route('/send/email', methods=['POST'])
def send_email():
to = request.form.get('to')

result = send_message(to)

return 'Email sent, response: <pre>{}</pre>'.format(result)


@app.errorhandler(500)
def server_error(e):
logging.exception('An error ocurred during a request.')
return """
An internal error occurred: <pre>{}</pre>
See logs for full stacktrace.
""".format(e), 500


if __name__ == '__main__':
# This is used when running locally. Gunicorn is used to run the
# application on Google App Engine. See entrypoint in app.yaml.
app.run(host='127.0.0.1', port=8080, debug=True)
# [END app]
53 changes: 53 additions & 0 deletions managed_vms/mailjet/main_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.

import re

import pytest
import responses


@pytest.fixture
def app(monkeypatch):
monkeypatch.setenv('MAILJET_API_KEY', 'apikey')
monkeypatch.setenv('MAILJET_API_SECRET', 'apisecret')
monkeypatch.setenv('MAILJET_SENDER', 'sender')

import main

main.app.testing = True
return main.app.test_client()


def test_index(app):
r = app.get('/')
assert r.status_code == 200


@responses.activate
def test_send_email(app):
responses.add(
responses.POST,
re.compile(r'.*'),
body='{"test": "message"}',
content_type='application/json')

r = app.post('/send/email', data={'to': 'user@example.com'})

assert r.status_code == 200
assert 'test' in r.data.decode('utf-8')

assert len(responses.calls) == 1
request_body = responses.calls[0].request.body
assert 'user@example.com' in request_body
4 changes: 4 additions & 0 deletions managed_vms/mailjet/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Flask==0.10.1
gunicorn==19.4.5
requests[security]==2.9.1
mailjet_rest==1.1.1
Loading

0 comments on commit 48a3be6

Please sign in to comment.