GMail API:无法在草稿中添加附件

时间:2014-06-26 11:28:24

标签: gmail-api

我可以使用GMail API创建简单的仅限HTML的草稿。

但是当我尝试上传附件时,它失败并出现以下错误:

{
  "code" : 500,
  "errors" : [ {
    "domain" : "global",
    "message" : "Backend Error",
    "reason" : "backendError"
  } ],
  "message" : "Backend Error"
}

这是我的代码,任何人都可以帮助我吗?

        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage email = new MimeMessage(session);
        InternetAddress tAddress = new InternetAddress("to@to.in");
        InternetAddress fAddress = new InternetAddress("from@from.in");

        email.setFrom(fAddress);
        email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
        email.setSubject("subject");

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent("thebody", "text/plain");
        mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(mimeBodyPart);

        mimeBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource("C:\\Users\\David\\Downloads\\test.pdf");

        mimeBodyPart.setDataHandler(new DataHandler(source));
        mimeBodyPart.setFileName("thepdf.pdf");
        String contentType = "application/pdf";
        mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + "test.pdf" + "\"");
        mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

        multipart.addBodyPart(mimeBodyPart);

        email.setContent(multipart);
        email.writeTo(System.out);

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        email.writeTo(bytes);
        String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
        Message message = new Message();
        message.setRaw(encodedEmail);

        Draft draft = new Draft();
        draft.setMessage(message);
        draft = new Gmail(new NetHttpTransport(), new JacksonFactory(), getCredential()).users().drafts().create("me", draft).execute();

3 个答案:

答案 0 :(得分:1)

我认为代码是合理的。你能提供email.writeTo(System.out)的输出来确认吗?好像是Gmail API中的错误。

对于任何特定用户,这是否可重复? (它总是失败还是最终会起作用?)

是针对所有用户还是仅针对某些用户(例如,是否适用于gmail.com用户而非适用于Google Apps用户)?

答案 1 :(得分:1)

第二天问题自行解决了!我不知道GMail API团队是否修复了某些内容,或者它是否是一个临时错误。

答案 2 :(得分:0)

尝试这个希望所以它的作品首先放置文本内容,然后在html内容之后正确显示

MimeBodyPart textPart = new MimeBodyPart();
        textPart.setText("This is actual message", "utf-8");

        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent("<h1>This is a test</h1>"
                + "<img src=\"http://www.rgagnon.com/images/jht.gif\">", "text/html; charset=utf-8");
        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(textPart);<--first 
        multipart.addBodyPart(htmlPart);<--seocnd 
        message.setContent(multipart)