我正在尝试使用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正确实现多文件上传吗?
正如您正确指出的,Simple file upload的最大附件大小为5 MB
结论:
您需要使用Multipart upload或Resumable 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发送电子邮件。