The Mail service API for Java supports the JavaMail
( javax.mail
) interface for
sending email messages.
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:
-
Create a message using a JavaMail
Session
object. -
Create a
MimeMessage
object. -
To set the message sender and recipient, use the
InternetAddress
class.-
Identify the sender by calling the
setFrom()
method on theMimeMessage
object. 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.CC
orMessage.RecipientType.BCC
.
The
InternetAddress
constructor raises anAddressException
if 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
MimeMessage
object. Set the subject withsetSubject()
and set the plaintext body content withsetText()
. -
To send the message, use the static method
send()
on theTransport
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:
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:
-
Create a
MimeMultipart
object to contain the parts, then create aMimeBodyPart
object 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:
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 .