无法使用gmail api

时间:2017-11-07 11:12:10

标签: java gmail-api

我第一次使用gmail api。我正在尝试使用gmail api保存草稿消息。 源代码类似如下,

String urlLink = "https://www.googleapis.com/upload/gmail/v1/users/" + emailSetting.getEmailId() + "/drafts?uploadType=media";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(urlLink);
        httpPost.setHeader("Content-Type", "message/rfc822");

        httpPost.setHeader("Authorization", "Bearer " + access_token);

        StringEntity params = new StringEntity(message.toString());
        httpPost.setEntity(params);
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

这里的消息是我用来准备消息json的JSONObject,如下所示,

        JSONObject jsonObject = new JSONObject();
        JSONObject message =new JSONObject();
        jsonObject.put("threadId", 001);
        jsonObject.put("snippet", msg.getSubject());

        // Prepare Header start 
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObj = new JSONObject();

        jsonObj.put("name", "Delivered-To");
        jsonObj.put("value", msg.getTo());
        jsonArray.put(jsonObj);

        jsonObj = new JSONObject();
        jsonObj.put("name", "To");
        //jsonObj.put("value", "<"+msg.getTo()+">");
        jsonObj.put("value", msg.getTo());
        jsonArray.put(jsonObj);

        jsonObj = new JSONObject();
        jsonObj.put("name", "From");
        jsonObj.put("value", emailSetting.getEmailId());
        jsonArray.put(jsonObj);

        jsonObj = new JSONObject();
        jsonObj.put("name", "Subject");
        jsonObj.put("value", msg.getSubject());
        jsonArray.put(jsonObj);

        jsonObj = new JSONObject();
        jsonObj.put("name", "Date");
        jsonObj.put("value", new java.util.Date());
        jsonArray.put(jsonObj);

        JSONObject headerJSONObject = new JSONObject();
        headerJSONObject.put("headers", jsonArray);

        jsonObject.put("payload", headerJSONObject);


        message.put("message", jsonObject);
        message.put("id", msg.getMessageId());

上面的代码以状态200执行。但是草稿消息是空的,即没有主题,没有“to”,也没有正文。如果有人对此源代码有任何建议,请分享,谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用此Users.drafts: create from the documentation。如果你还没有尝试过。

  

使用DRAFT标签创建新草稿。 Try it nowsee an example

     

此方法支持 / upload URI并接受上传的媒体   具有以下特点:

     
      
  • 最大文件大小: 35MB
  •   
  • 接受的媒体MIME类型: message/rfc822
  •   

以下是java code provided in the documentation示例。

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;
  }

  // ...

}