-
Notifications
You must be signed in to change notification settings - Fork 64
sending mail with 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.
Register your sender emails as authorized senders. For more information, see who can send email.
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:
-
Create a message using a JavaMail
Sessionobject. -
Create a
MimeMessageobject. -
To set the message sender and recipient, use the
InternetAddressclass.-
Identify the sender by calling the
setFrom()method on theMimeMessageobject. Optionally, you can provide a personal name as a string in the second parameter. -
Identify the recipient by passing a recipient type and an address to the
addRecipient()method. The recipient type can beMessage.RecipientType.TO,Message.RecipientType.CCorMessage.RecipientType.BCC.
The
InternetAddressconstructor raises anAddressExceptionif the email address appears to be invalid. -
-
To set a "reply to" address, use the
setReplyTo()method. -
Establish the contents of the message by calling methods on the
MimeMessageobject. Set the subject withsetSubject()and set the plaintext body content withsetText(). -
To send the message, use the static method
send()on theTransportclass.
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.
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:
-
Create a
MimeMultipartobject to contain the parts, then create aMimeBodyPartobject for each attachment or alternate message body and add it to the container.' -
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.
To send mail from your application:
-
Use the
mail.Messagetype to set the sender, recipient, subject, and body of the message. -
Send the email with the
mail.Sendfunction.
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
`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.
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:
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.
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.