Users.drafts: create

Requires authorization

Creates a new draft with the DRAFT label. 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/drafts
  • Metadata URI, for metadata-only requests:
    POST https://www.googleapis.com/gmail/v1/users/userId/drafts

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:
  • media - Simple upload. Upload the media only, without any metadata.
  • multipart - Multipart upload. Upload both the media and its metadata, in a single request.
  • resumable - Resumable upload. Upload the file in a resumable fashion, using a series of at least two requests where the first request includes the metadata.

Authorization

This request requires authorization with at least one of the following scopes (read more about authentication and authorization).

Scope
https://mail.google.com/
https://www.googleapis.com/auth/gmail.modify
https://www.googleapis.com/auth/gmail.compose

Request body

In the request body, supply a Users.drafts resource as the metadata. For more information, see the document on media upload.

Response

If successful, this method returns a Users.drafts 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.Draft;
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 {

  // ...

  /**
   * Create draft email.
   *
   * @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 MimeMessage used as email within Draft.
   * @return Created Draft.
   * @throws MessagingException
   * @throws IOException
   */
  public static Draft createDraft(Gmail service, String userId, MimeMessage email)
      throws MessagingException, IOException {
    Message message = createMessageWithEmail(email);
    Draft draft = new Draft();
    draft.setMessage(message);
    draft = service.users().drafts().create(userId, draft).execute();

    System.out.println("draft id: " + draft.getId());
    System.out.println(draft.toPrettyString());
    return draft;
  }

  /**
   * 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>
  /// Create draft email.
  /// </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 used within Draft.</param>
  public static Draft CreateDraft(GmailService service, String userId, Message email)
  {
      Draft draft = new Draft();
      draft.Message = email;

      try
      {
          return service.Users.Drafts.Create(draft, userId).Execute();
      }
      catch (Exception e)
      {
          Console.WriteLine("An error occurred: " + e.Message);
      }

      return null;
  }

  // ...

}

PHP

Does not use a client library.

/**
 * Create Draft email.
 *
 * @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 of the created Draft.
 * @return Google_Service_Gmail_Draft Created Draft.
 */
function createDraft($service, $user, $message) {
  $draft = new Google_Service_Gmail_Draft();
  $draft->setMessage($message);
  try {
    $draft = $service->users_drafts->create($user, $draft);
    print 'Draft ID: ' . $draft->getId();
  } catch (Exception $e) {
    print 'An error occurred: ' . $e->getMessage();
  }
  return $draft;
}


/**
 * Create a Message from an email formatted string.
 *
 * @param  string $email Email formatted string.
 * @return Google_Service_Gmail_Message Message containing email.
 */
function createMessage($email) {
  $message = new Google_Service_Gmail_Message();
  // base64url encode the string
  //   see http://en.wikipedia.org/wiki/Base64#Implementations_and_history
  $email = strtr(base64_encode($email), array('+' => '-', '/' => '_'));
  $message->setRaw($email);
  return $message;
}

Python

Uses the Python client library.

"""Generates and submits an email as a draft.
"""

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 CreateDraft(service, user_id, message_body):
  """Create and insert a draft email. Print the returned draft's message and id.

  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_body: The body of the email message, including headers.

  Returns:
    Draft object, including draft id and message meta data.
  """
  try:
    message = {'message': message_body}
    draft = service.users().drafts().create(userId=user_id, body=message).execute()

    print 'Draft id: %s\nDraft message: %s' % (draft['id'], draft['message'])

    return draft
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
    return None


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: The email address of the sender.
    to: The 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.

/**
 * Create Draft email.
 *
 * @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 createDraft(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.drafts.create({
    'userId': userId,
    'resource': {
      'message': {
        '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.

フィードバックを送信...

ご不明な点がありましたら、Google のサポートページをご覧ください。