Notice: Over the next few months, we're reorganizing the App Engine documentation site to make it easier to find content and better align with the rest of Google Cloud products. The same content will be available, but the navigation will now match the rest of the Cloud products.

Sending and Receiving Mail with the Mail API

Stay organized with collections Save and categorize content based on your preferences.

This guide describes how to use the Mail API to send and receive mail.

Before you begin

You must register your sender emails as authorized senders. For more information, see who can send email.

Sending mail

To send mail from your application:

  1. Use the mail.Message type to set the sender, recipient, subject, and body of the message.

  2. Send the email with the mail.Send function.

The following example sends an email message to the user as a confirmation that they have created a new account with the application:

import (
	"bytes"
	"fmt"
	"net/http"

	"google.golang.org/appengine"
	"google.golang.org/appengine/log"
	"google.golang.org/appengine/mail"
)

func confirm(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	addr := r.FormValue("email")
	url := createConfirmationURL(r)
	msg := &mail.Message{
		Sender:  "Example.com Support <support@example.com>",
		To:      []string{addr},
		Subject: "Confirm your registration",
		Body:    fmt.Sprintf(confirmMessage, url),
	}
	if err := mail.Send(ctx, msg); err != nil {
		log.Errorf(ctx, "Couldn't send email: %v", err)
	}
}

const confirmMessage = `
Thank you for creating an account!
Please confirm your email address by clicking on the link below:

%s
`

Receiving mail

You can set up your app to receive incoming email at addresses in the following format:

anything@appid.appspotmail.com

To receive email:

  1. Enable incoming mail in your app's app.yaml file:

    inbound_services:
    - mail
  2. Set up a handler to process incoming emails, which are supplied to your app as MIME data in an HTTP POST request.

    1. In your app, register a handler to the /_ah/mail/ path:

      func init() {
      	http.HandleFunc("/_ah/mail/", incomingMail)
      }
      
    2. In the handler, read the email's data from the *http.Request:

      func incomingMail(w http.ResponseWriter, r *http.Request) {
      	ctx := appengine.NewContext(r)
      	defer r.Body.Close()
      	var b bytes.Buffer
      	if _, err := b.ReadFrom(r.Body); err != nil {
      		log.Errorf(ctx, "Error reading body: %v", err)
      		return
      	}
      	log.Infof(ctx, "Received mail: %v", b)
      }
      

    You can use the net/mail package in the standard library to parse mail messages.