Sends the specified message to the recipients in the
To
, Cc
, and Bcc
headers.
Try it now or see an example.
This method supports an /upload URI and accepts uploaded media with the following characteristics:
- Maximum file size: 35MB
- Accepted Media MIME types:
message/rfc822
Request
HTTP request
This method provides media upload functionality through two separate URIs. For more details, see the document on media upload.
- Upload URI, for media upload requests:
POST https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send
- Metadata URI, for metadata-only requests:
POST https://www.googleapis.com/gmail/v1/users/userId/messages/send
Parameters
Parameter name | Value | Description |
---|---|---|
Path parameters | ||
userId |
string |
The user's email address. The special value me
can be used to indicate the authenticated user.
|
Required query parameters | ||
uploadType |
string |
The type of upload request to the /upload URI.
Acceptable values are:
|
Authorization
This request requires authorization with at least one of the following scopes:
Scope |
---|
https://mail.google.com/ |
https://www.googleapis.com/auth/gmail.modify |
https://www.googleapis.com/auth/gmail.compose |
https://www.googleapis.com/auth/gmail.send |
For more information, see the authentication and authorization page.
Request body
In the request body, supply a Users.messages resource with the following properties as the metadata. For more information, see the document on media upload.
Property name | Value | Description | Notes |
---|---|---|---|
Required Properties | |||
raw |
bytes |
The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in messages.get and drafts.get responses when the format=RAW parameter is supplied. |
writable |
Optional Properties | |||
threadId |
string |
The ID of the thread the message belongs to. To add a message or draft to a thread, the following criteria must be met:
|
writable |
Response
If successful, this method returns a Users.messages resource in the response body.
Examples
Note: The code examples available for this method do not represent all supported programming languages (see the client libraries page for a list of supported languages).
Java
Uses the Java client library.
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64; import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.model.Message; import java.io.IOException; import java.io.InputStream; import java.nio.file.FileSystems; import java.nio.file.Files; import java.util.Enumeration; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; // ... public class MyClass { // ... /** * Send an email from the user's mailbox to its recipient. * * @param service Authorized Gmail API instance. * @param userId User's email address. The special value "me" * can be used to indicate the authenticated user. * @param email Email to be sent. * @throws MessagingException * @throws IOException */ public static void sendMessage(Gmail service, String userId, MimeMessage email) throws MessagingException, IOException { Message message = createMessageWithEmail(email); message = service.users().messages().send(userId, message).execute(); System.out.println("Message id: " + message.getId()); System.out.println(message.toPrettyString()); } /** * Create a Message from an email * * @param email Email to be set to raw of message * @return Message containing base64url encoded email. * @throws IOException * @throws MessagingException */ public static Message createMessageWithEmail(MimeMessage email) throws MessagingException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); email.writeTo(baos); String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray()); Message message = new Message(); message.setRaw(encodedEmail); return message; } // ... }
.NET
Uses the .NET client library.
using Google.Apis.Gmail.v1; using Google.Apis.Gmail.v1.Data; // ... public class MyClass { // ... /// <summary> /// Send an email from the user's mailbox to its recipient. /// </summary> /// <param name="service">Gmail API service instance.</param> /// <param name="userId">User's email address. The special value "me" /// can be used to indicate the authenticated user.</param> /// <param name="email">Email to be sent.</param> public static Message SendMessage(GmailService service, String userId, Message email) { try { return service.Users.Messages.Send(email, userId).Execute(); } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); } return null; } // ... }
PHP
Does not use a client library.
/** * Send Message. * * @param Google_Service_Gmail $service Authorized Gmail API instance. * @param string $userId User's email address. The special value 'me' * can be used to indicate the authenticated user. * @param Google_Service_Gmail_Message $message Message to send. * @return Google_Service_Gmail_Message sent Message. */ function sendMessage($service, $userId, $message) { try { $message = $service->users_messages->send($userId, $message); print 'Message with ID: ' . $message->getId() . ' sent.'; return $message; } catch (Exception $e) { print 'An error occurred: ' . $e->getMessage(); } }
Python
Uses the Python client library.
"""Send an email message from the user's account. """ import base64 from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import mimetypes import os from apiclient import errors def SendMessage(service, user_id, message): """Send an email message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. message: Message to be sent. Returns: Sent Message. """ try: message = (service.users().messages().send(userId=user_id, body=message) .execute()) print 'Message Id: %s' % message['id'] return message except errors.HttpError, error: print 'An error occurred: %s' % error def CreateMessage(sender, to, subject, message_text): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. Returns: An object containing a base64url encoded email object. """ message = MIMEText(message_text) message['to'] = to message['from'] = sender message['subject'] = subject return {'raw': base64.urlsafe_b64encode(message.as_string())} def CreateMessageWithAttachment(sender, to, subject, message_text, file_dir, filename): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. file_dir: The directory containing the file to be attached. filename: The name of the file to be attached. Returns: An object containing a base64url encoded email object. """ message = MIMEMultipart() message['to'] = to message['from'] = sender message['subject'] = subject msg = MIMEText(message_text) message.attach(msg) path = os.path.join(file_dir, filename) content_type, encoding = mimetypes.guess_type(path) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) if main_type == 'text': fp = open(path, 'rb') msg = MIMEText(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'image': fp = open(path, 'rb') msg = MIMEImage(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'audio': fp = open(path, 'rb') msg = MIMEAudio(fp.read(), _subtype=sub_type) fp.close() else: fp = open(path, 'rb') msg = MIMEBase(main_type, sub_type) msg.set_payload(fp.read()) fp.close() msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg) return {'raw': base64.urlsafe_b64encode(message.as_string())}
JavaScript
Does not use a client library.
/** * Send Message. * * @param {String} userId User's email address. The special value 'me' * can be used to indicate the authenticated user. * @param {String} email RFC 5322 formatted String. * @param {Function} callback Function to call when the request is complete. */ function sendMessage(userId, email, callback) { // Using the js-base64 library for encoding: // https://www.npmjs.com/package/js-base64 var base64EncodedEmail = Base64.encodeURI(email); var request = gapi.client.gmail.users.messages.send({ 'userId': userId, 'resource': { 'raw': base64EncodedEmail } }); request.execute(callback); }
Try it!
Note: APIs Explorer currently supports metadata requests only.
Use the APIs Explorer below to call this method on live data and see the response.