使用Java Gmail API发送带有多个(大型)附件的电子邮件

时间:2019-12-29 17:48:56

标签: java google-api gmail-api email-attachments

我正在尝试使用Google Gmail API(Java)创建包含多个附件的电子邮件。使用下面的代码,我可以发送嵌入在MimeMessage if 中的多个附件,这些附件的总大小小于5MB(Google的简单文件上传阈值)。

com.google.api.services.gmailGmail service = (... defined above ...)
javax.mail.internet.MimeMessage message = (... defined above with attachments embedded ...)

// Send the email
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
mimeMessage.writeTo(buffer);
byte[] bytes = buffer.toByteArray();
String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
Message message = new Message();
message.setRaw(encodedEmail);

message = service.users().messages().send("me", message).execute();

但是,我无法弄清楚如何使用Gmail Java API将多个文件正确地附加到电子邮件中。下面的方法看起来很有希望,但似乎只接受1个File / InputStream(mediaContent)。

Gmail.Users.Messages.Send send(userId, Message content, AbstractInputStreamContent mediaContent)

任何人都知道如何使用API​​正确实现多文件上传吗?

2 个答案:

答案 0 :(得分:1)

正如您正确指出的那样,Simple file upload的最大附件大小为5 MB

结论:

您需要使用Multipart uploadResumable upload

发送包含分段上传的电子邮件的示例:

public static MimeMessage createEmailWithAttachment(String to, String from, String subject,
                                      String bodyText,String filePath) throws MessagingException{
    File file = new File(filePath);
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage email = new MimeMessage(session);
    Multipart multipart = new MimeMultipart();
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);
    email.setFrom(fAddress);
    email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
    email.setSubject(subject);
    if (file.exists()) {
        source = new FileDataSource(filePath);
        messageFilePart = new MimeBodyPart();
        messageBodyPart = new MimeBodyPart();
        try {
            messageBodyPart.setText(bodyText);
            messageFilePart.setDataHandler(new DataHandler(source));
            messageFilePart.setFileName(file.getName());

            multipart.addBodyPart(messageBodyPart);
            multipart.addBodyPart(messageFilePart);
            email.setContent(multipart);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }else
        email.setText(bodyText);
    return email;
}

Here,您可以找到许多其他有用的示例,这些示例可用于通过Java中的Gmail API发送电子邮件。

答案 1 :(得分:1)

事实证明,我的MimeMessage是正确生成的,但是,如果MimeMessage中包含的附件​​大于5MB,则需要使用其他Gmail API send()方法。 API文档令人难以置信,因为它们似乎表明您需要对其余端点进行多次调用才能上载多个文件。事实证明,Gmail Java Api根据提交的MimeMessage为您完成了所有工作。

下面是一个代码片段,显示了如何使用两种方法:“简单上传”和“分段上传”。

com.google.api.services.gmailGmail service = (... defined above ...)
javax.mail.internet.MimeMessage message = (... defined above with attachments embedded ...)

/**
 * Send email using Gmail API - dynamically uses simple or multipart send depending on attachments size
 * 
 * @param mimeMessage MimeMessage (includes any attachments for the email)
 * @param attachments the Set of files that were included in the MimeMessage (if any).  Only used to calculate total size to see if we should use "simple" send or need to use multipart upload.
 */
void send(MimeMessage mimeMessage, @Nullable Set<File> attachments) throws Exception {

    Message message = new Message();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    mimeMessage.writeTo(buffer);

    // See if we need to use multipart upload
    if (attachments!=null && computeTotalSizeOfAttachments(attachments) > BYTES_5MB) {

        ByteArrayContent content = new ByteArrayContent("message/rfc822", buffer.toByteArray());
        message = service.users().messages().send("me", null, content).execute();

    // Otherwise, use "simple" send
    } else {

        String encodedEmail = Base64.encodeBase64URLSafeString(buffer.toByteArray());
        message.setRaw(encodedEmail);
        message = service.users().messages().send("me", message).execute();
    }

    System.out.println("Gmail Message: " + message.toPrettyString());
}