Sending Emails with SendGrid

You can use SendGrid to power your emails on Google App Engine. SendGrid can improve your deliverability and provide transparency into what actually happens to those emails your app sends. You can see statistics on opens, clicks, unsubscribes, spam reports and more with the SendGrid interface or its API.

Pricing

Google App Engine customers can send 12,000 emails every month for free. Create a SendGrid account to claim the free emails and to select higher volume plans. Note that Google will be compensated for customers who sign up for a paid account.

SendGrid libraries

You can send email with SendGrid through an SMTP relay or using a Web API.

Setting up

To use SendGrid to send an email:

  1. Select or create a new Cloud Platform project in the Google Cloud Platform Console and then ensure an App Engine application exists and billing is enabled:

    Go to App Engine

    The Dashboard opens if an App Engine application already exists in your project and billing is enabled. Otherwise, follow the prompts for choosing a region and enabling billing.
  2. Create a SendGrid account.
  3. Add your SendGrid settings to the configuration variables in appsettings.json.

    For example, for the sample code below add:

    "ApiKey": "your-sendgrid-api-key"
    

Example

You can create a SendGrid instance and use it to send mail. The following sample code shows how to send an email and specifies some error handling:

Task<HttpResponseMessage> CallSendGrid(string recipient)
{
    // As of 2017-02-09, the sendgrid Nuget package is not compatible
    // with .net core.  So, this code follows the web api spec:
    // https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html
    // If you're using more sendgrid features, consider using swagger
    // to generate a client from:
    // https://github.com/sendgrid/sendgrid-oai
    var request = new
    {
        personalizations = new[] {
            new {
                to = new[]
                {
                    new {email = recipient}
                },
                subject = "Hello World!"
            }
        },
        from = new
        {
            email = "alice@example.com"
        },
        content = new[]
        {
            new {
                type = "text/plain",
                value = "Hello, World!"
            }
        }
    };
    HttpClient sendgrid3 = new HttpClient();
    sendgrid3.DefaultRequestHeaders.Authorization = 
        new System.Net.Http.Headers.AuthenticationHeaderValue(
            "Bearer", _sendgridApiKey);
    string jsonRequest = JsonConvert.SerializeObject(request);
    return sendgrid3.PostAsync("https://api.sendgrid.com/v3/mail/send",
        new StringContent(jsonRequest, System.Text.Encoding.UTF8, 
        "application/json"));
}

Add your own account details, and then edit the email address and other message content.

For more email settings and examples, see the SendGrid Web API documentation.

Testing and Deploying

Visual Studio

To test your application locally:

  1. In Visual Studio, open dotnet-docs-samples\appengine\flexible\AppEngineFlex.sln.
  2. Press F5.

To deploy your application:

  1. In Solution Explorer, right-click SendGrid, and choose Publish SendGrid to Google Cloud...
  2. Click App Engine Flex.
  3. Click Publish.

Command Line

To test your application locally:

  1. Run the following commands from the dotnet-docs-samples\appengine\flexible\ directory:
    dotnet restore
    dotnet run
  2. In your web browser, navigate to http://localhost:5000/
  3. In your terminal window, press Ctrl+C to exit the web server.

To deploy your application:

  1. Navigate to the dotnet-docs-samples\appengine\flexible\ directory.
  2. Run the following commands:
    dotnet restore
    dotnet publish
    gcloud beta app deploy .\bin\Debug\netcoreapp1.0\publish\app.yaml

Getting real-time information

In addition to sending email, SendGrid can help you receive email or make sense of the email you’ve already sent. The two real-time webhook solutions can greatly enhance the role email plays in your application.

Event API

Once you start sending email from your application, you can view statistics collected by SendGrid to assess your email program. You can use the Event API to see this data. For example, whenever a recipient opens or clicks an email, SendGrid can send a small bit of descriptive JSON to your Google App Engine app. You can react to the event or store the data for future use.

You can use this event data in many different ways, such as integrating email stats into internal dashboards or responding immediately to unsubscribes and spam reports. Advanced users of the Event API raise the engagement of their emails by sending only to those who have clicked or opened within the last few months.

The Event API documentation shows how to set up the webhook, outlines the nine event types and shows the fields included in event callbacks.

Inbound Parse API

SendGrid excels at sending email, but it can also receive email. The Inbound Parse API can be used for powerful, interactive applications. For example, automate support tickets from customer emails, or collect data via short emails employees dispatch from the road. NudgeMail's reminder application is even built entirely on the Parse API.

Like the Event API, the Parse API is a webhook that sends data to your application when something new is available. In this case, the webhook is called whenever a new email arrives at the domain you've associated with incoming email. Due to intricacies in the way DNS works for email, you need to assign all incoming mail to the domain or subdomain you use for the Parse API.

Emails are sent to your application structured as JSON, with sender, recipients, subject and body as different fields. You can even accept attachments, within SendGrid’s limit of messages up to 20 MB in size.

The Parse API documentation has more details, including additional fields sent with every email, as well as instructions for DNS setup and usage.

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

App Engine flexible environment for .NET docs