Users.drafts: update

Requires authorization

Replaces a draft's content. 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:
    PUT https://www.googleapis.com/upload/gmail/v1/users/userId/drafts/id
  • Metadata URI, for metadata-only requests:
    PUT https://www.googleapis.com/gmail/v1/users/userId/drafts/id

Parameters

Parameter name Value Description
Path parameters
id string The ID of the draft to update.
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 {

  // ...


  /**
   * Update 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 draftId ID of Draft to update.
   * @param updatedEmail Updated email to be sent.
   * @throws MessagingException
   * @throws IOException
   */
  public static void updateDraft(Gmail service, String userId, String draftId,
      MimeMessage updatedEmail) throws MessagingException, IOException {
    Message updatedMessage = new Message();
    updatedMessage.setRaw(encodeEmail(updatedEmail));

    Draft updatedDraft = new Draft();
    updatedDraft.setMessage(updatedMessage);

    updatedDraft = service.users().drafts().update(userId, draftId, updatedDraft)
        .execute();

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

  /**
   * Encode the MimeMessage into a base64url encoded string.
   *
   * @param email MimeMessage email to be encoded.
   * @return base64url encoded string of the MimeMessage.
   * @throws MessagingException
   * @throws java.io.IOException
   */
  public static String encodeEmail(MimeMessage email) throws MessagingException, IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    email.writeTo(baos);
    return Base64.encodeBase64URLSafeString(baos.toString().getBytes());
  }

  // ...

}

.NET

Uses the .NET client library.

using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;

// ...

public class MyClass {

  // ...

  /// <summary>
  /// Update 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="draftId">ID of the draft to update.</param>
  /// <param name="updatedEmail">Updated email to be sent.</param>
  /// <param name="send">Send email if true, do not send otherwise.</param>
  public static Draft UpdateDraft(GmailService service, String userId, String draftId, Message updatedEmail, Boolean send)
  {
      Draft draft = new Draft();
      draft.Message = updatedEmail;

      try
      {
          UsersResource.DraftsResource.UpdateRequest request = service.Users.Drafts.Update(draft, userId, draftId);
          request.Send = send;
          return request.Execute();
      }
      catch (Exception e)
      {
          Console.WriteLine("An error occurred: " + e.Message);
      }

      return null;
  }

  // ...

}

PHP

Does not use a client library.

/**
 * Replace Message within Draft with given ID.
 *
 * @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  string $draftId Id of draft to be updated.
 * @param  Google_Service_Gmail_Draft $updatedMessage Message used to update draft.
 * @param  boolean $send Whether or not to send Draft once updated.
 * @return Google_Service_Gmail_Draft Updated Draft.
 */
function updateDraft($service, $userId, $draftId, $updatedMessage, $send) {
  $opt_param = array('send' => $send);
  $draft = new Google_Service_Gmail_Draft();
  $draft->setMessage($updatedMessage);
  try {
    $draft = $service->users_drafts->update($userId, $draftId, $draft, $opt_param);
    print 'Draft with ID: ' . $draftId . ' updated successfully.';
  } catch (Exception $e) {
    print 'An error occurred: ' . $e->getMessage();
  }

  return $draft;
}

Python

Uses the Python client library.

"""Updates a draft with specified draft id.
"""

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 UpdateDraft(service, user_id, draft_id, message_body, send):
  """Create and update a draft email.

  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.
    draft_id: ID of the draft to Update.
    message_body: The body of the email message, including headers.
    send: Send draft if 1 otherwise don't send draft.

  Returns:
    Updated draft object.
  """
  try:
    message = {'message': message_body}
    draft = service.users().drafts().update(userId=user_id, id=draft_id,
                                            body=message, send=send).execute()

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

    return draft
  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: 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.

  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.

/**
 * Replace Message within Draft with given ID.
 *
 * @param  {String} userId User's email address. The special value 'me'
 * can be used to indicate the authenticated user.
 * @param  {String} draftId ID of Draft to update.
 * @param  {String} updatedEmail RFC 5322 formatted String.
 * @param  {Boolean} send Send or not send Draft once updated.
 * @param  {Function} callback Function to call when the request is complete.
 */
function updateDraft(userId, draftId, updatedEmail, send, callback) {
  // Using the js-base64 library for encoding:
  // https://www.npmjs.com/package/js-base64
  var base64UpdatedEmail = Base64.encodeURI(email);
  var request = gapi.client.gmail.users.drafts.update({
    'userId': userId,
    'id': draftId,
    'resource': {
      'id': draftId,
      'message': {
        'raw': base64UpdatedEmail
      }
    },
    'send': send
  });
  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 のサポートページをご覧ください。