Java 8 ha raggiunto la fine del supporto
e verrà
ritirato
il 31 gennaio 2026. Dopo il ritiro, non potrai eseguire il deployment di applicazioni Java 8, anche se la tua organizzazione ha utilizzato in precedenza un criterio dell'organizzazione per riattivare i deployment di runtime legacy. Le tue applicazioni Java 8 esistenti continueranno a essere eseguite e a ricevere traffico dopo la
data di ritiro. Ti consigliamo di
eseguire la migrazione all'ultima versione supportata di Java.
Invio di email con l'API Mail
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
L'API del servizio Mail per Java supporta l'interfaccia
JavaMail (javax.mail
) per l'invio di messaggi email.
Prima di iniziare
Registra le email del mittente come mittenti autorizzati. Per ulteriori informazioni, vedi
Chi può inviare email.
Invio di messaggi email
Per inviare messaggi email, utilizza le classi JavaMail incluse nell'SDK App Engine.
Quando crei una sessione JavaMail, se non fornisci alcuna configurazione del server SMTP, App Engine utilizza il servizio Mail per l'invio dei messaggi.
In alternativa, aggiungi la configurazione SMTP per i provider di posta di terze parti supportati, come Mailgun, Mailjet o SendGrid.
Per inviare un messaggio:
Crea un messaggio utilizzando un oggetto JavaMail Session
.
Crea un oggetto MimeMessage
.
Per impostare il mittente e il destinatario del messaggio, utilizza la classe InternetAddress
.
Identifica il mittente chiamando il metodo setFrom()
sull'oggetto
MimeMessage
. Se vuoi, puoi fornire un nome personale come
stringa nel secondo parametro.
Identifica il destinatario passando un tipo di destinatario e un indirizzo al metodo
addRecipient()
. Il tipo di destinatario può essere
Message.RecipientType.TO
, Message.RecipientType.CC
o
Message.RecipientType.BCC
.
Il costruttore InternetAddress
genera un AddressException
se l'indirizzo email
non sembra valido.
Per impostare un indirizzo "Rispondi a", utilizza il metodo setReplyTo()
.
Stabilisci i contenuti del messaggio chiamando i metodi sull'oggetto
MimeMessage
. Imposta l'oggetto con setSubject()
e imposta
il contenuto del corpo in testo normale con setText()
.
Per inviare il messaggio, utilizza il metodo statico send()
nella classe Transport
.
Il servizio Mail ti consente di specificare un insieme limitato di intestazioni nei messaggi email in uscita. Per saperne di più, consulta la sezione Intestazioni facoltative che puoi
utilizzare.
Il seguente esempio di codice mostra come inviare posta:
Le chiamate al servizio di posta sono asincrone e vengono restituite immediatamente. Il servizio
Mail gestisce la procedura di contatto con i server di posta dei destinatari e
il recapito del messaggio. Se si verifica un problema durante l'invio del messaggio a un destinatario o se il server di posta di un destinatario restituisce un messaggio di "mancato recapito", il messaggio di errore viene inviato al mittente.
Invio di messaggi in più parti
Puoi inviare messaggi in più parti, ad esempio un messaggio con allegati o un messaggio con un corpo del messaggio in testo normale e un corpo del messaggio in HTML.
Per inviare un messaggio in più parti:
Crea un oggetto MimeMultipart
per contenere le parti, poi crea un oggetto
MimeBodyPart
per ogni allegato o corpo del messaggio alternativo e aggiungilo
al contenitore.
Assegna il contenitore ai contenuti per MimeMessage
.
Il seguente esempio di codice mostra come inviare un messaggio in più parti:
Per motivi di sicurezza, le parti dei messaggi e gli allegati devono essere di uno dei diversi tipi consentiti e i nomi file degli allegati devono terminare con un'estensione del nome file riconosciuta per il tipo. Per un elenco dei tipi e delle estensioni dei nomi di file consentiti, vedi
Email con allegati.
Salvo quando diversamente specificato, i contenuti di questa pagina sono concessi in base alla licenza Creative Commons Attribution 4.0, mentre gli esempi di codice sono concessi in base alla licenza Apache 2.0. Per ulteriori dettagli, consulta le norme del sito di Google Developers. Java è un marchio registrato di Oracle e/o delle sue consociate.
Ultimo aggiornamento 2025-09-04 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 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)."]]