Esistono due modi per inviare email utilizzando l'API Gmail:
- Puoi inviarlo direttamente utilizzando il
messages.send
. - Puoi inviarlo da bozza utilizzando
drafts.send
.
Le email vengono inviate come stringhe codificate base64url all'interno della proprietà raw
di un
risorsa di messaggistica. La configurazione di alto livello
del flusso di lavoro per inviare un'email prevede:
- Crea i contenuti dell'email in un modo pratico e codificali come stringa base64url.
- Crea una nuova risorsa di messaggio e imposta la relativa proprietà
raw
su base64url la stringa appena creata. - Chiama il numero
messages.send
oppure, se stai inviando una bozza,drafts.send
per inviare il messaggio.
I dettagli di questo flusso di lavoro possono variare a seconda del client scelto libreria e linguaggio di programmazione.
Creazione dei messaggi
L'API Gmail richiede messaggi email MIME conformi RFC 2822 e codificate come stringhe base64url. Molti linguaggi di programmazione hanno librerie o utilità che semplificano il processo di creazione e codifica MIME messaggi. I seguenti esempi di codice mostrano come creare un messaggio MIME utilizzando le librerie client delle API di Google per vari linguaggi.
Java
La creazione di un'email può essere notevolmente semplificata con il MimeMessage
nel pacchetto javax.mail.internet
. L'esempio seguente mostra come
per creare il messaggio email, incluse le intestazioni:
Il passaggio successivo prevede la codifica di MimeMessage
, la creazione di un'istanza di un Message
e imposta la stringa di messaggio codificata base64url come valore del valore
proprietà raw
.
Python
Il seguente esempio di codice mostra la creazione di un messaggio MIME, la codifica per
una stringa base64url e assegnandola al campo raw
di Message
risorsa:
Creazione di messaggi con allegati
Creare un messaggio con un allegato è come creare qualsiasi altro messaggio, ma la procedura per caricare il file come file MIME multiparte dipende dal linguaggio di programmazione. Il seguente codice esempi mostrano possibili modi per creare un messaggio MIME multiparte con in un allegato.
Java
L'esempio seguente mostra come creare un messaggio MIME multiparte, i passaggi di codifica e assegnazione sono gli stessi indicati sopra.
Python
Analogamente all'esempio precedente, anche in questo esempio viene gestita la codifica
messaggio a base64url e assegnandolo al campo raw
di Message
risorsa.
l'invio di un messaggio e un altro
Una volta creato un messaggio, puoi inviarlo fornendolo nel
richiedi il corpo di una chiamata a
messages.send
, come dimostrato
nei seguenti esempi.
Java
Python
Se stai cercando di inviare una risposta e vuoi che l'email sia in thread, assicurati che:
- Le intestazioni
Subject
corrispondono - Le intestazioni
References
eIn-Reply-To
seguono le RFC 2822.
Per informazioni sull'invio di un messaggio da una bozza, vedi Creazione di bozze.