【问题标题】:Create a draft with PDF file as attachment using Gmail API in Java使用 Java 中的 Gmail API 创建带有 PDF 文件作为附件的草稿
【发布时间】:2019-12-06 01:04:33
【问题描述】:

我正在尝试使用 Gmail API 在 Java 中创建带有附件的 草稿

创建一个基本的草稿作品,所以我已经消除了任何许可问题。 我使用代码 here 作为灵感,但无法让它发挥作用。

这是我到目前为止所做的:

public String generateGmailDraft(EmailRequestDto emailRequestDto, String quoteId) 
        throws MessagingException, IOException, GeneralSecurityException {
    // The attachment is a PDF file
    AttachmentDto lastQuoteData = getLastQuotePdfData(quoteId);

    MimeMessage email = createMimeMessage(emailRequestDto, lastQuoteData);
    Message messageWithEmail = createMessageWithEmail(email);

    Draft draft = new Draft();
    draft.setMessage(messageWithEmail);

    // this works
    Gmail gmail = gmail(googleGmailCredentialProperties);

    log.debug("attempting to send mail");
    draft = gmail.users().drafts().create(emailRequestDto.getFrom(), draft).execute();

    log.debug("Draft id: {}", draft.getMessage().getId());
    log.debug(draft.toPrettyString());

    return draft.getMessage().getId();
}


从 Google 示例中,我创建了一条 MIME 消息,但这可能是问题所在:

/**
 * Create a MimeMessage using the parameters provided
 * @return the MimeMessage to be used to send email
 * @throws MessagingException
 */
private MimeMessage createMimeMessage(EmailRequestDto requestDto, AttachmentDto attachment)
        throws MessagingException, IOException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    email.setFrom(new InternetAddress(requestDto.getFrom()));
    email.addRecipient(javax.mail.Message.RecipientType.TO, ew InternetAddress(requestDto.getTo()));
    email.setSubject(requestDto.getSubject());

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setHeader("Content-Type", "multipart/alternative");
    messageBodyPart.setText(requestDto.getBody());  // Setting the actual message

    // Create a multipart message and set text message part
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    // Try to add an attachment
    MimeBodyPart attachmentBP = new MimeBodyPart();
    attachmentBP.setFileName(attachment.fileName);

    ByteArrayOutputStream baos = attachmentToByteArrayOutputStream(attachment.file);
    DataSource dataSrc = new ByteArrayDataSource(baos.toByteArray(), "application/pdf");
    attachmentBP.setDataHandler(new DataHandler(dataSrc));
    multipart.addBodyPart(attachmentBP);

    // Send the complete message parts
    email.setContent(multipart);

    return email;
}


这个私有类有望提供附件所需的一切,使用时,所有私有字段都正确填写。

/**
AttachmentDTO returns everything needed to create an attachment
- file
- mimeype
- filename
- inputstream : used because file can come from different sources in the app.
*/ 
private static final class AttachmentDto {

    private final InputStream inputStream;
    private final String fileName;
    private File file;
    private String mimeType;

    private AttachmentDto(InputStream inputStream, String fileName) {
        this.inputStream = inputStream;
        this.fileName = fileName;

        File outputFile = new File(fileName);
        try (OutputStream out = new FileOutputStream(outputFile)) {
            IOUtils.copy(inputStream, out);
            file = outputFile;
            mimeType = Files.probeContentType(outputFile.toPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public String getFileName() {
        return fileName;
    }

    public File getFile() {
        return file;
    }

    public String getMimeType() {
        return mimeType;
    }
}


当前状态:

  • 代码卡在gmail.users().drafts().create(emailRequestDto.getFrom(), draft).execute(); 并且永远不会返回
  • 按照上面的链接,我还尝试将附件编码为 Base64,然后使用

    public Gmail.Users.Drafts.Create create( String userId, Draft content, AbstractInputStreamContent mediaContent) throws java.io.IOException

    我想,当你有附件时使用的对应物。

  • 当我使用它时,草稿会在我的邮箱中创建,但没有附件。

感谢您的帮助。

【问题讨论】:

    标签: java gmail attachment email-attachments mime


    【解决方案1】:

    尝试类似的方法:

    private MimeMessage createEmailWithAttachment(String to,
            String subject,
            String bodyText,
            File file) throws MessagingException, IOException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
    
        MimeMessage email = new MimeMessage(session);
    
        email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
        email.setSubject(subject);
    
        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(bodyText, "text/plain");
    
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(mimeBodyPart);
    
        mimeBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(file);
    
        mimeBodyPart.setDataHandler(new DataHandler(source));
        mimeBodyPart.setFileName(file.getName());
    
        multipart.addBodyPart(mimeBodyPart);
        email.setContent(multipart);
    
        return email;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-24
      • 2021-04-27
      • 2016-06-09
      • 2017-05-01
      • 2018-04-19
      • 1970-01-01
      • 2014-08-17
      • 2018-02-20
      • 2016-09-27
      相关资源
      最近更新 更多