Skip to content

sending mail with mail api

ludoch edited this page Apr 15, 2026 · 2 revisions

Sending mail with the Mail API

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

The Mail API for Java supports the JavaMail (javax.mail) interface for sending email messages.

The Mail API provides two ways to send an email message: the mail.send_mail() function and the EmailMessage class.

Sending is asynchronous: the mail.send_mail() function and the EmailMessage.send() method transmit the message data to the mail service, then return. The mail service queues the message, then attempts to send it, retrying if the destination mail server is unavailable. Errors and bounce messages are sent to the sender address for the email message.

Before you begin

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

Sending email messages

To send email messages, use the JavaMail classes included with the App Engine SDK.

When you create a JavaMail Session, if you do not provide any SMTP server configuration, App Engine uses the Mail service for sending messages. Alternatively, add SMTP configuration for supported third-party mail providers such as Mailgun, Mailjet, or SendGrid.

To send a message:

  1. Create a message using a JavaMail Session object.

  2. Create a MimeMessage object.

  3. To set the message sender and recipient, use the InternetAddress class.

    1. Identify the sender by calling the setFrom() method on the MimeMessage object. Optionally, you can provide a personal name as a string in the second parameter.

    2. Identify the recipient by passing a recipient type and an address to the addRecipient() method. The recipient type can be Message.RecipientType.TO, Message.RecipientType.CC or Message.RecipientType.BCC.

    The InternetAddress constructor raises an AddressException if the email address appears to be invalid.

  4. To set a "reply to" address, use the setReplyTo() method.

  5. Establish the contents of the message by calling methods on the MimeMessage object. Set the subject with setSubject() and set the plaintext body content with setText().

  6. To send the message, use the static method send() on the Transport class.

The Mail service allows you to specify a limited set of headers on outgoing email messages. For more information, see Optional headers you can use.

The following code sample demonstrates how to send mail:

View MailServlet.java on GitHub (region: simple_example)

Calls to the Mail service are asynchronous and return immediately. The Mail service manages the process of contacting the recipients' mail servers and delivering the message. If there is a problem sending the message to any recipient, or if a recipient's mail server returns a "bounce" message, the error message goes to the sender.

Sending multi-part messages

You can send multi-part messages, such as a message with file attachments, or a message with a plaintext message body and an HTML message body.

To send a multi-part message:

  1. Create a MimeMultipart object to contain the parts, then create a MimeBodyPart object for each attachment or alternate message body and add it to the container.'

  2. Assign the container to the content for MimeMessage.

The following code sample demonstrates how to send a multi-part message:

View MailServlet.java on GitHub (region: multipart_example)

For security purposes, message parts and attachments must be of one of several allowed types, and attachment filenames must end in a recognized filename extension for the type. For a list of allowed types and filename extensions, see Mail with attachments.

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/v2"
        "google.golang.org/appengine/v2/log"
        "google.golang.org/appengine/v2/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
`

Sending mail

In PHP 7/8, the App Engine Mail function is no longer overloaded by default, and must be explicitly enabled. This new behavior lets you repurpose the Mail function to better suit your needs. This change also allows you to have visibility into which implementation is currently being used for all Mail function calls.

If you prefer using the native PHP mail() function to send mail using the App Engine Mail API, you can enable it in your php.ini file as follows:

extension = mailparse.so
sendmail_path = "php ./vendor/google/appengine-php-sdk/src/Runtime/SendMail.php -t -i"

Alternatively, you can make direct calls to the Mail API:

// Notice that $image_content_id is the optional Content-ID header value of the
// attachment. Must be enclosed by angle brackets (<>)
$image_content_id = '<image-content-id>';

// Pull in the raw file data of the image file to attach it to the message.
$image_data = file_get_contents('image.jpg');

try {
    $message = new Message();
    $message->setSender('from@example.com');
    $message->addTo('to@example.com');
    $message->setSubject('Example email');
    $message->setTextBody('Hello, world!');
    $message->addAttachment('image.jpg', $image_data, $image_content_id);
    $message->send();
    echo 'Mail Sent';
} catch (InvalidArgumentException $e) {
    echo 'There was an error';

Learn more about the migration considerations for the Mail API in the Accessing legacy bundled services for PHP guide.

Sending mail with mail.send_mail()

To send mail using the mail.send_mail() function, use the fields of the email message as parameters, including the sender, the recipients, the subject and the body of the message. For example:

Sending mail with EmailMessage

To send mail using objects with the EmailMessage class, pass the fields of the email message to the EmailMessage constructor and use attributes of the instance to update message.

The EmailMessage.send() method sends the email message represented by the instance's attributes. An application can re-use an EmailMessage instance by modifying attributes and calling the send() method again.

Sending bulk mail

See the Bulk mail guidelines for considerations around sending bulk email.

Learn more about the migration considerations for Mail API in the Mail handlers guide.

Clone this wiki locally