Skip to content

Commit dab28c0

Browse files
Merge branch 'audreylm-patch-1'
2 parents 03e0679 + d62b623 commit dab28c0

3 files changed

Lines changed: 376 additions & 0 deletions

File tree

use_cases/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ This directory provides examples for specific use cases of this library. Please
55
## Table of Contents
66

77
### How-Tos
8+
9+
* [How to Create a Django app, Deployed on Heroku, to Send Email with SendGrid](django.md)
10+
* [How to Deploy A Simple Hello Email App on AWS](aws.md)
811
* [How to Setup a Domain Whitelabel](domain_whitelabel.md)
912
* [How to View Email Statistics](email_stats.md)
1013

use_cases/aws.md

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
# Deploy a simple Hello Email app on AWS
2+
3+
This tutorial explains how to set up a simple "Hello Email" app on AWS, using the AWS CodeStar service.
4+
5+
We'll be creating a basic web service to send email via SendGrid. The application will run on AWS Lambda, and the "endpoint" will be via AWS API Gateway.
6+
7+
The neat thing is that CodeStar provides all of this in a pre-configured package. We just have to make some config changes, and push our code.
8+
9+
Once this tutorial is complete, you'll have a basic web service for sending email that can be invoked via a link to your newly created API endpoint.
10+
11+
### Prerequisites
12+
Python 2.6, 2.7, 3.4, or 3.5 are supported by the sendgrid Python library, however I was able to utilize 3.6 with no issue.
13+
14+
Before starting this tutorial, you will need to have access to an AWS account in which you are allowed to provision resources. This tutorial also assumes you've already created a SendGrid account with free-tier access. Finally, it is highly recommended you utilize [virtualenv](https://virtualenv.pypa.io/en/stable/).
15+
16+
*DISCLAIMER*: Any resources provisioned here may result in charges being incurred to your account. Sendgrid is in no way responsible for any billing charges.
17+
18+
19+
## Getting Started
20+
21+
### Create AWS CodeStar Project
22+
Log in to your AWS account and go to the AWS CodeStar service. Click "Start a project". For this tutorial we're going to choose a Python Web service, utilizing AWS Lambda. You can use the filters on the left hand side of the UI to narrow down the available choices.
23+
24+
After you've selected the template, you're asked to provide a name for your project. Go ahead and name it "hello-email". Once you've entered a name, click "Create Project" in the lower right hand corner. You can then choose which tools you want to use to interact with the project. For this tutorial, we'll be choosing "Command Line".
25+
26+
Once that is completed, you'll be given some basic steps to get Git installed and setup, and instructions for connecting to the AWS CodeCommit(git) repository. You can either use HTTPS, or SSH. Instructions for setting up either are provided.
27+
28+
Go ahead and clone the Git repository link after it is created. You may need to click "Skip" in the lower right hand corner to proceed.
29+
30+
Once that's done, you've successfully created a CodeStar project! You should be at the dashboard, with a view of the wiki, change log, build pipeline, and application endpoint.
31+
32+
### Create SendGrid API Key
33+
Log in to your SendGrid account. Click on your user name on the left hand side of the UI and choose "Setup Guide" from the drop-down menu. On the "Welcome" menu, choose "Send Your First Email", and then "Integrate using our Web API or SMTP relay." Choose "Web API" as the recommended option on the next screen, as we'll be using that for this tutorial. For more information about creating API keys, see https://sendgrid.com/docs/Classroom/Send/How_Emails_Are_Sent/api_keys.html
34+
35+
On the next menu, you have the option to choose what programming language you'll be using. The obvious choice for this tutorial will be Python.
36+
37+
Follow the steps on the next screen. Choose a name for your API key, such as "hello-email". Follow the remaining steps to create an environment variable, install the sendgrid module, and copy the test code. Once that is complete, check the "I've integrated the code above" box, and click the "Next: Verify Integration" button.
38+
39+
Assuming all the steps were completed correctly, you should be greeted with a success message. If not, go back and verify that everything is correct, including your API key environment varible, and Python code.
40+
41+
## Deploy hello-world app using CodeStar
42+
43+
For the rest of the tutorial, we'll be working out of the git repository we cloned from AWS earlier:
44+
```
45+
$ cd hello-email
46+
```
47+
note: this assumes you cloned the git repo inside your current directory. My directory is:
48+
49+
```
50+
~/projects/hello-email
51+
```
52+
53+
The directory contents should be as follows:
54+
55+
├──buildspec.yml
56+
├──index.py
57+
├──template.yml
58+
├──README.md
59+
60+
The `buildspec.yml` file is a YAML definition for the AWS CodeBuild service, and will not need to be modified for this tutorial. The `index.py` is where the application logic will be placed, and the `template.yml` is a YAML definition file for the AWS Lambda function.
61+
62+
We'll start by modifying the `template.yml` file. Copy and paste from the example below, or edit your existing copy to match:
63+
64+
```yaml
65+
AWSTemplateFormatVersion: 2010-09-09
66+
Transform:
67+
- AWS::Serverless-2016-10-31
68+
- AWS::CodeStar
69+
70+
Parameters:
71+
ProjectId:
72+
Type: String
73+
Description: CodeStar projectId used to associate new resources to team members
74+
75+
Resources:
76+
HelloEmail:
77+
Type: AWS::Serverless::Function
78+
Properties:
79+
Handler: index.handler
80+
Runtime: python3.6
81+
Role:
82+
Fn::ImportValue:
83+
!Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
84+
Events:
85+
GetEvent:
86+
Type: Api
87+
Properties:
88+
Path: /
89+
Method: get
90+
PostEvent:
91+
Type: Api
92+
Properties:
93+
Path: /
94+
Method: post
95+
```
96+
97+
In the root project directory, run the following commands:
98+
```
99+
virtualenv venv
100+
source ./venv/bin/activate
101+
```
102+
103+
Prior to being able to deploy our Python code, we'll need to install the sendgrid Python module *locally*. One of the idiosyncracies of AWS Lambda is that all library and module dependencies that aren't part of the standard library have to be included with the code/build artifact. Virtual environments do not translate to the Lambda runtime environment.
104+
105+
In the root project directory, run the following command:
106+
```
107+
$ pip install sendgrid -t .
108+
```
109+
This will install the module locally to the project dir, where it can be built into the Lambda deployment.
110+
111+
Now go ahead and modify the `index.py` file to match below:
112+
113+
```python
114+
import json
115+
import datetime
116+
import sendgrid
117+
import os
118+
from sendgrid.helpers.mail import *
119+
120+
def handler(event, context):
121+
sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
122+
from_email = Email("test@example.com")
123+
to_email = Email("test@example.com")
124+
subject = "Sending with SendGrid is Fun"
125+
content = Content("text/plain", "and easy to do anywhere, even with Python")
126+
mail = Mail(from_email, subject, to_email, content)
127+
response = sg.client.mail.send.post(request_body=mail.get())
128+
status = b"{}".decode('utf-8').format(response.status_code)
129+
body = b"{}".decode('utf-8').format(response.body)
130+
headers = b"{}".decode('utf-8').format(response.headers)
131+
data = {
132+
'status': status,
133+
'body': body,
134+
'headers': headers.splitlines(),
135+
'timestamp': datetime.datetime.utcnow().isoformat()
136+
}
137+
return {'statusCode': 200,
138+
'body': json.dumps(data),
139+
'headers': {'Content-Type': 'application/json'}}
140+
```
141+
142+
Note that for the most part, we've simply copied the intial code from the API verification with SendGrid. Some slight modifications were needed to allow it to run as a lambda function, and for the output to be passed cleanly from the API endpoint.
143+
144+
Change the `test@example.com` emails appropriately so that you may receive the test email.
145+
146+
Go ahead and commit/push your code:
147+
148+
```
149+
$ git add .
150+
```
151+
152+
```
153+
$ git commit -m 'hello-email app'
154+
```
155+
156+
```
157+
$ git push
158+
```
159+
160+
Once the code is successfully pushed, head back to the AWS CodeStar dashboard for your project. After your commit successfully registers, an automated build and deployment process should kick off.
161+
162+
One more step left before our application will work correctly. After your code has bee deployed, head to the AWS Lambda console. Click on your function name, which should start with `awscodestar-hello-email-lambda-`, or similar.
163+
164+
Scroll down to the "Environment Variables" section. Here we need to populate our SendGrid API key. Copy the value from the `sendgrid.env` file you created earlier, ensuring to capture the entire value. Make sure the key is titled:
165+
166+
```
167+
SENDGRID_API_KEY
168+
```
169+
170+
Now, go back to your project dashboard in CodeStar. Click on the link under "Application endpoints". After a moment, you should be greeted with JSON output indicating an email was successfully sent.
171+
172+
Congratulations, you've just used serverless technology to create an email sending app in AWS!

use_cases/django.md

Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
# Create a Django app to send email with SendGrid
2+
3+
This tutorial explains how we set up a simple Django app to send an email with the SendGrid Python SDK and how we deploy our app to Heroku.
4+
5+
## Create a Django project
6+
7+
We first create a project folder.
8+
9+
```bash
10+
$ mkdir hello-sendgrid
11+
$ cd hello-sendgrid
12+
```
13+
14+
We assume you have created and activated a [virtual environment](https://virtualenv.pypa.io/) (See [venv](https://docs.python.org/3/tutorial/venv.html) for Python 3+) for isolated Python environments.
15+
16+
Run the command below to install Django, Gunicorn (a Python WSGI HTTP server), and SendGrid Python SDK.
17+
18+
```bash
19+
$ pip install django gunicorn sendgrid
20+
```
21+
22+
It's a good practice for Python dependency management. We'll pin the requirements with a file `requirements.txt`.
23+
24+
```bash
25+
$ pip freeze > requirements.txt
26+
```
27+
28+
Run the command below to initialize a Django project.
29+
30+
```bash
31+
$ django-admin startproject hello_sendgrid
32+
```
33+
34+
The folder structure should look like this:
35+
36+
```
37+
hello-sendgrid
38+
├── hello_sendgrid
39+
│   ├── hello_sendgrid
40+
│   │   ├── __init__.py
41+
│   │   ├── settings.py
42+
│   │   ├── urls.py
43+
│   │   └── wsgi.py
44+
│   └── manage.py
45+
└── requirements.txt
46+
```
47+
48+
Let's create a page to generate and send an email to a user when you hit the page.
49+
50+
We first create a file `views.py` and put it under the folder `hello_sendgrid/hello_sendgrid`. Add the minimum needed code below.
51+
52+
```python
53+
import os
54+
55+
from django.http import HttpResponse
56+
57+
import sendgrid
58+
from sendgrid.helpers.mail import *
59+
60+
61+
def index(request):
62+
sg = sendgrid.SendGridAPIClient(
63+
apikey=os.environ.get('SENDGRID_API_KEY')
64+
)
65+
from_email = Email('test@example.com')
66+
to_email = Email('test@example.com')
67+
subject = 'Sending with SendGrid is Fun'
68+
content = Content(
69+
'text/plain',
70+
'and easy to do anywhere, even with Python'
71+
)
72+
mail = Mail(from_email, subject, to_email, content)
73+
response = sg.client.mail.send.post(request_body=mail.get())
74+
75+
return HttpResponse('Email Sent!')
76+
```
77+
78+
**Note:** It would be best to change your to email from `test@example.com` to your own email, so that you can see the email you receive.
79+
80+
Now the folder structure should look like this:
81+
82+
```
83+
hello-sendgrid
84+
├── hello_sendgrid
85+
│   ├── hello_sendgrid
86+
│   │   ├── __init__.py
87+
│   │   ├── settings.py
88+
│   │   ├── urls.py
89+
│   │   ├── views.py
90+
│   │   └── wsgi.py
91+
│   └── manage.py
92+
└── requirements.txt
93+
```
94+
95+
Next we open the file `urls.py` in order to add the view we have just created to the Django URL dispatcher.
96+
97+
```python
98+
from django.conf.urls import url
99+
from django.contrib import admin
100+
101+
from .views import index
102+
103+
104+
urlpatterns = [
105+
url(r'^admin/', admin.site.urls),
106+
url(r'^sendgrid/', index, name='sendgrid'),
107+
]
108+
```
109+
110+
These paths allow the URL `/sendgrid/` to send the email.
111+
112+
We also assume that you have set up your development environment with your `SENDGRID_API_KEY`. If you have not done it yet, please do so. See the section [Setup Environment Variables](https://github.com/sendgrid/sendgrid-python#setup-environment-variables).
113+
114+
Now we should be able to send an email. Let's run our Django development server to test it.
115+
116+
```
117+
$ cd hello_sengrid
118+
$ python manage.py migrate
119+
$ python manage.py runserver
120+
```
121+
122+
By default, it starts the development server at `http://127.0.0.1:8000/`. To test if we can send email or not, go to `http://127.0.0.1:8000/sendgrid/`. If it works, we should see the page says "Email Sent!".
123+
124+
**Note:** If you use `test@example.com` as your from email, it's likely to go to your spam folder. To have the emails show up in your inbox, try using an email address at the domain you registered your SendGrid account.
125+
126+
## Deploy to Heroku
127+
128+
There are different deployment methods we can choose. In this tutorial, we choose to deploy our app using the [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli). Therefore, let's install it before we go further.
129+
130+
Once you have the Heroku CLI installed, run the command below to log in to your Heroku account if you haven't already.
131+
132+
```
133+
$ heroku login
134+
```
135+
136+
Before we start the deployment, let's create a Heroku app by running the command below. This tutorial names the Heroku app `hello-sendgrid`.
137+
138+
```bash
139+
$ heroku create hello-sendgrid
140+
```
141+
142+
**Note:** If you see Heroku reply with "Name is already taken", please add a random string to the end of the name.
143+
144+
We also need to do a couple things:
145+
146+
1. Add `'*'` or your Heroku app domain to `ALLOWED_HOSTS` in the file `settings.py`. It will look like this:
147+
```python
148+
ALLOWED_HOSTS = ['*']
149+
```
150+
151+
2. Add `Procfile` with the code below to declare what commands are run by your application's dynos on the Heroku platform.
152+
```
153+
web: cd hello_sendgrid && gunicorn hello_sendgrid.wsgi --log-file -
154+
```
155+
156+
The final folder structure looks like this:
157+
158+
```
159+
hello-sendgrid
160+
├── hello_sendgrid
161+
│   ├── hello_sendgrid
162+
│   │   ├── __init__.py
163+
│   │   ├── settings.py
164+
│   │   ├── urls.py
165+
│   │   ├── views.py
166+
│   │   └── wsgi.py
167+
│   └── manage.py
168+
├── Procfile
169+
└── requirements.txt
170+
```
171+
172+
Go to the root folder then initialize a Git repository.
173+
174+
```
175+
$ git init
176+
$ heroku git:remote -a hello-sendgrid
177+
```
178+
179+
**Note:** Change `hello-sendgrid` to your new Heroku app name you created earlier.
180+
181+
Add your `SENDGRID_API_KEY` as one of the Heroku environment variables.
182+
183+
```
184+
$ heroku config:set SENDGRID_API_KEY=<YOUR_SENDGRID_API_KEY>
185+
```
186+
187+
Since we do not use any static files, we will disable `collectstatic` for this project.
188+
189+
```
190+
$ heroku config:set DISABLE_COLLECTSTATIC=1
191+
```
192+
193+
Commit the code to the repository and deploy it to Heroku using Git.
194+
195+
```
196+
$ git add .
197+
$ git commit -am "Create simple Hello Email Django app using SendGrid"
198+
$ git push heroku master
199+
```
200+
201+
After that, let's verify if our app is working or not by accessing the root domain of your Heroku app. You should see the page says "Email Sent!" and on the Activity Feed page in the SendGrid dashboard, you should see a new feed with the email you set in the code.

0 commit comments

Comments
 (0)