Mengirim Email dengan Mail API
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Mail service API untuk Java mendukung antarmuka JavaMail (javax.mail
) untuk mengirim pesan email.
Sebelum memulai
Daftarkan email pengirim Anda sebagai pengirim yang sah. Untuk informasi selengkapnya, lihat siapa yang dapat mengirim email.
Mengirim pesan email
Untuk mengirim pesan email, gunakan class JavaMail yang disertakan dengan App Engine
SDK.
Ketika Anda membuat Sesi JavaMail, jika Anda tidak memberikan konfigurasi server SMTP apa pun, App Engine akan menggunakan layanan Email untuk mengirim pesan.
Atau, tambahkan konfigurasi SMTP untuk penyedia email pihak ketiga yang didukung, seperti Mailgun, Mailjet, atau SendGrid.
Untuk mengirim pesan:
Buat pesan menggunakan objek Session
JavaMail.
Buat objek MimeMessage
.
Untuk menetapkan pengirim dan penerima pesan, gunakan class InternetAddress
.
Identifikasi pengirim dengan memanggil metode setFrom()
pada objek MimeMessage
. Jika ingin, Anda dapat memberikan nama pribadi sebagai
string di parameter kedua.
Identifikasi penerima dengan meneruskan jenis dan alamat penerima ke metode addRecipient()
. Jenis penerima dapat berupa
Message.RecipientType.TO
, Message.RecipientType.CC
, atau
Message.RecipientType.BCC
.
Konstruktor InternetAddress
memunculkan AddressException
jika alamat email tampak tidak valid.
Untuk menetapkan alamat "balas ke", gunakan metode setReplyTo()
.
Buat konten pesan dengan memanggil metode pada objek MimeMessage
. Tetapkan subjek dengan setSubject()
dan tetapkan
konten isi teks biasa dengan setText()
.
Untuk mengirim pesan, gunakan metode statis send()
pada class
Transport
.
Dengan layanan Email, Anda dapat menentukan set header terbatas pada pesan email keluar. Untuk informasi selengkapnya, lihat Header opsional yang dapat Anda
gunakan.
Contoh kode berikut menunjukkan cara mengirim email:
Panggilan ke layanan Email bersifat asinkron dan ditampilkan segera. Layanan Email mengelola proses menghubungi server email penerima dan mengirimkan pesan. Jika ada masalah saat mengirim pesan ke penerima mana pun, atau jika server email penerima menampilkan pesan "email tidak terkirim", pesan error akan dikirimkan kepada pengirim.
Mengirim pesan multi-bagian
Anda dapat mengirim pesan yang terdiri dari beberapa bagian, seperti pesan dengan lampiran file, atau pesan dengan isi pesan teks biasa dan isi pesan HTML.
Untuk mengirim pesan multi-bagian:
Buat objek MimeMultipart
untuk menampung bagian-bagiannya, lalu buat objek MimeBodyPart
untuk setiap lampiran atau isi pesan alternatif, dan tambahkan ke container.'
Tetapkan container ke konten untuk MimeMessage
.
Contoh kode berikut menunjukkan cara mengirim pesan multi-bagian:
Untuk tujuan keamanan, bagian serta lampiran pesan harus salah satu dari beberapa jenis yang diizinkan, dan nama file lampiran harus diakhiri dengan ekstensi nama file yang dikenali untuk jenis tersebut. Untuk daftar jenis dan ekstensi nama file yang diizinkan, lihat
Email dengan lampiran.
Kecuali dinyatakan lain, konten di halaman ini dilisensikan berdasarkan Lisensi Creative Commons Attribution 4.0, sedangkan contoh kode dilisensikan berdasarkan Lisensi Apache 2.0. Untuk mengetahui informasi selengkapnya, lihat Kebijakan Situs Google Developers. Java adalah merek dagang terdaftar dari Oracle dan/atau afiliasinya.
Terakhir diperbarui pada 2025-09-04 UTC.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-09-04 UTC."],[[["\u003cp\u003eThe Java Mail service API supports the \u003ccode\u003ejavax.mail\u003c/code\u003e interface for sending email messages within first-generation runtimes, with migration options for second-generation runtimes.\u003c/p\u003e\n"],["\u003cp\u003eTo send emails, you need to create a JavaMail \u003ccode\u003eSession\u003c/code\u003e object and a \u003ccode\u003eMimeMessage\u003c/code\u003e object, and configure the sender and recipients using the \u003ccode\u003eInternetAddress\u003c/code\u003e class.\u003c/p\u003e\n"],["\u003cp\u003eApp Engine can use its own Mail service for sending messages if no SMTP server is configured, but it also supports third-party providers like Mailgun, Mailjet, and SendGrid.\u003c/p\u003e\n"],["\u003cp\u003eYou can send multi-part messages, including file attachments and messages with both plaintext and HTML bodies, by using \u003ccode\u003eMimeMultipart\u003c/code\u003e and \u003ccode\u003eMimeBodyPart\u003c/code\u003e objects.\u003c/p\u003e\n"],["\u003cp\u003eThe Mail service handles contacting recipients' mail servers and delivering messages asynchronously, with error messages or bounces going to the sender.\u003c/p\u003e\n"]]],[],null,["# Sending Mail with the Mail API\n\nThe Mail service API for Java supports the\n[JavaMail](http://www.oracle.com/technetwork/java/javamail/index.html) (`javax.mail`) interface for\nsending email messages.\n\n\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| java-gen2\n|\n| /services/access). If you are updating to the App Engine Java 11/17 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/java-differences) to learn about your migration options for legacy bundled services.\n\n\u003cbr /\u003e\n\nBefore you begin\n----------------\n\nRegister your sender emails as authorized senders. For more information, see\n[who can send email](/appengine/docs/legacy/standard/java/mail#who_can_send_mail).\n\nSending email messages\n----------------------\n\nTo send email messages, use the JavaMail classes included with the App Engine\nSDK.\n\nWhen you create a JavaMail Session, if you do not provide any SMTP server\nconfiguration, App Engine uses the Mail service for sending messages.\nAlternatively, add SMTP configuration for supported third-party mail\nproviders such as [Mailgun](/appengine/docs/legacy/standard/java/mail/mailgun),\n[Mailjet](/appengine/docs/legacy/standard/java/mail/mailjet), or\n[SendGrid](/appengine/docs/legacy/standard/java/mail/sendgrid).\n\nTo send a message:\n\n1. Create a message using a JavaMail `Session` object.\n\n2. Create a `MimeMessage` object.\n\n3. To set the message sender and recipient, use the `InternetAddress` class.\n\n 1. Identify the sender by calling the `setFrom()` method on the\n `MimeMessage` object. Optionally, you can provide a personal name as a\n string in the second parameter.\n\n 2. Identify the recipient by passing a recipient type and an address to the\n `addRecipient()` method. The recipient type can be\n `Message.RecipientType.TO`, `Message.RecipientType.CC` or\n `Message.RecipientType.BCC`.\n\n The `InternetAddress` constructor raises an `AddressException` if the email\n address appears to be invalid.\n4. To set a \"reply to\" address, use the `setReplyTo()` method.\n\n5. Establish the contents of the message by calling methods on the\n `MimeMessage` object. Set the subject with `setSubject()` and set the\n plaintext body content with `setText()`.\n\n6. To send the message, use the static method `send()` on the `Transport`\n class.\n\nThe Mail service allows you to specify a limited set of headers on outgoing\nemail messages. For more information, see [Optional headers you can\nuse](/appengine/docs/legacy/standard/java/mail/mail-with-headers-attachments#optional_headers_you_can_use).\n\nThe following code sample demonstrates how to send mail: \n\n Properties props = new Properties();\n Session session = Session.getDefaultInstance(props, null);\n\n try {\n Message msg = new MimeMessage(session);\n msg.setFrom(new InternetAddress(\"admin@example.com\", \"Example.com Admin\"));\n msg.addRecipient(Message.RecipientType.TO,\n new InternetAddress(\"user@example.com\", \"Mr. User\"));\n msg.setSubject(\"Your Example.com account has been activated\");\n msg.setText(\"This is a test\");\n Transport.send(msg);\n } catch (AddressException e) {\n // ...\n } catch (MessagingException e) {\n // ...\n } catch (UnsupportedEncodingException e) {\n // ...\n }\n\nCalls to the Mail service are asynchronous and return immediately. The Mail\nservice manages the process of contacting the recipients' mail servers and\ndelivering the message. If there is a problem sending the message to any\nrecipient, or if a recipient's mail server returns a \"bounce\" message, the error\nmessage goes to the sender.\n\nSending multi-part messages\n---------------------------\n\nYou can send multi-part messages, such as a message with file attachments, or a\nmessage with a plaintext message body and an HTML message body.\n\nTo send a multi-part message:\n\n1. Create a `MimeMultipart` object to contain the parts, then create a\n `MimeBodyPart` object for each attachment or alternate message body and add\n it to the container.'\n\n2. Assign the container to the content for `MimeMessage`.\n\nThe following code sample demonstrates how to send a multi-part message: \n\n String htmlBody = \"\"; // ...\n byte[] attachmentData = null; // ...\n Multipart mp = new MimeMultipart();\n\n MimeBodyPart htmlPart = new MimeBodyPart();\n htmlPart.setContent(htmlBody, \"text/html\");\n mp.addBodyPart(htmlPart);\n\n MimeBodyPart attachment = new MimeBodyPart();\n InputStream attachmentDataStream = new ByteArrayInputStream(attachmentData);\n attachment.setFileName(\"manual.pdf\");\n attachment.setContent(attachmentDataStream, \"application/pdf\");\n mp.addBodyPart(attachment);\n\n msg.setContent(mp);\n\nFor security purposes, message parts and attachments must be of one of several\nallowed types, and attachment filenames must end in a recognized filename\nextension for the type. For a list of allowed types and filename extensions, see\n[Mail with attachments](/appengine/docs/legacy/standard/java/mail/mail-with-headers-attachments#mail_with_attachments)."]]