为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Java 中的 Gmail API 创建带有 PDF 文件作为附件的草稿

使用 Java 中的 Gmail API 创建带有 PDF 文件作为附件的草稿

烙印99 2023-04-26 13:51:09
我正在尝试使用 Gmail API 在 Java 中创建带有附件的草稿。创建一个基本的草稿是有效的,所以我已经消除了任何权限问题。我在这里使用代码作为灵感,但无法让它发挥作用。这是我到目前为止所做的: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");}
查看完整描述

1 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

尝试与此类似的操作:


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;

}


查看完整回答
反对 回复 2023-04-26
  • 1 回答
  • 0 关注
  • 131 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信