【发布时间】:2016-05-24 06:24:44
【问题描述】:
我已尝试使用以下代码创建带有大附件的多部分电子邮件:
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeBodyPart mimeBodyText = new MimeBodyPart();
mimeBodyText.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
mimeBodyText.setContent(body, "text/html");
Multipart mp = new MimeMultipart();
mp.addBodyPart(mimeBodyText);
if (attachments != null && attachments.size() > 0) {
for (Uri uri : attachments) {
MimeBodyPart mimeBodyAttachment = new MimeBodyPart();
String fileName = UriUtils.getFileName(uri, context);
String mimeType = UriUtils.getMimeType(uri, context);
Log.d(TAG, "Generating file info, uri=" + uri.getPath() + ", mimeType=" + mimeType);
FileInputStream is = UriUtils.generateFileInfo(context, uri, mimeType);
if (is == null) {
throw new MessagingException("Failed to get file for uri=" + uri.getPath());
}
try
{
mimeBodyAttachment.setFileName(fileName);
mimeBodyAttachment.setHeader("Content-Type", mimeType + "; name=\"" + fileName + "\"");
DataSource source = new ByteArrayDataSource(is, mimeType);
mimeBodyAttachment.setDataHandler(new DataHandler(source));
mimeBodyAttachment.setHeader("Content-Transfer-Encoding", "base64");
mimeBodyAttachment.setDisposition(MimeBodyPart.ATTACHMENT);
mp.addBodyPart(mimeBodyAttachment);
} catch (IOException e) {
throw new MessagingException(e.getMessage());
}
}
}
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(from));
mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
mimeMessage.setSubject(subject);
mimeMessage.setContent(mp);
Message message = createMessageWithEmail(mimeMessage);
service.users().messages().send(from, message).execute();
这与this guide 中的内容非常相似,但是,当我尝试添加大于 ~5mb 的文件时,执行函数挂起并且不返回(我预计会出现错误或至少超时,但这是另一个问题)
经过一番搜索,我发现我需要以某种方式执行upload 请求(see here),Gmail API 中的以下 API 看起来不错:
Send send(java.lang.String userId, com.google.api.services.gmail.model.Message content, com.google.api.client.http.AbstractInputStreamContent mediaContent)
很遗憾,我找不到任何有关其用法的文档或说明。
当我尝试将附件原始设置为mediaContent 时,我收到一条错误消息,指出唯一支持的mime 类型是message/rfc822,所以我尝试采用MimeBodyPart 我在上面的for 循环中创建并使用它,但看起来附件只是被忽略了。
应该如何使用Gmail client API 和“上传”附件?
【问题讨论】:
-
@pratz9999 是的,我做到了,但这指的是 http 请求,而我正在询问应该简化 API 使用的客户端 API。
-
@pratz9999 感谢您的帮助,我从使用 SMTP 开始,但由于 Google “提供”了一个不错的
Gmail API,我认为使用它会更好,不幸的是,就像他们的许多 API 一样,文档太糟糕了,除非您需要最佳实践,否则您将需要一些 3rd 方的帮助才能使其发挥作用。 -
我同意你的观点。在处理许多 google API 时,我不得不接受 3rd 方的支持以进行更多的增强和改进。