Search code examples
gmailgmail-api

Gmail API: How to move a draft into INBOX, like we can do in Gmail UI


The Gmail API docs states that

Messages and threads can have multiple labels associated with them; however, draft messages cannot have labels applied to them.

However, we can move a draft to inbox using Gmail web UI.

I would like to do the same thing using API. How can this be done?


Solution

  • Thanks to @DalmTo, I found a solution as below.

    message = email.mime.text.MIMEText("This is the body")
    message['to'] = "[email protected]"
    message['from'] = "[email protected]"
    message['subject'] = "Test draft"
    payload1 = {"message": {
        "raw": base64.urlsafe_b64encode(message.as_bytes()).decode("utf-8"),
        # "labelIds": ["INBOX"]  # This will cause an error
        }}
    res1 = google.post("/gmail/v1/users/me/drafts", json=payload1)
        
    payload2 = {"addLabelIds": ["INBOX"], "removeLabelIds":[]}
    thread_id = res1.json()["message"]["threadId"]
    res2 = google.post(f"/gmail/v1/users/me/threads/{thread_id}/modify", json=payload2)
    # Or (both works)
    # message_id = res1.json()["message"]["id"]
    # res2 = google.post(f"/gmail/v1/users/me/messages/{thread_id}/modify", json=payload2)