有没有办法使用GMail api以html格式检索邮件正文?
我已经通过了message.get
..试图改变文档format
PARAMS到full
,minimal
和raw
.但是id并没有帮助.它返回邮件正文.
格式值说明:
"full":返回有效内容字段中已解析的电子邮件内容,并且不使用原始字段.(默认)
"minimal":仅返回标识符和标签等电子邮件元数据,不返回电子邮件标题,正文或有效内容.
"raw":以字符串形式返回原始字段中的整个电子邮件内容,并且不使用有效内容字段.这包括标识符,标签,元数据,MIME结构和小体部分(通常小于2KB).
我们不能简单地以html格式获取邮件正文,或者是否有其他方法可以做到这一点,以便当他们在我的应用程序或GMail中看到邮件时,屏幕上显示的邮件差别很小?
Eri*_*eda 20
具有HTML和纯文本内容的电子邮件将具有多个有效负载部分,而具有mimeType"text/html"的部分将包含HTML内容.您可以使用以下逻辑找到它:
var part = message.parts.filter(function(part) {
return part.mimeType == 'text/html';
});
var html = urlSafeBase64Decode(part.body.data);
Run Code Online (Sandbox Code Playgroud)
FULL和RAW都会根据您的喜好返回任何文本/ html部分.如果你使用FULL,你将得到一个解析的表示,它将是嵌套的json词典,你必须走过去寻找text/html部分.如果您选择RAW格式,您将在Message.raw字段中以RFC822格式获取整个电子邮件.您可以使用您选择的语言将其传递给mime库,然后使用它来查找您感兴趣的部分.Mime很复杂,您可能会有一个顶级的"multipart"类型,其中text/html为直接的孩子,但没有保证,这是一个任意深度的树结构!:)
这是完整的教程:
1- 假设您已经在此处完成了所有凭据创建
2- 这是您检索 Mime 消息的方式:
public static String getMimeMessage(String messageId)
throws Exception {
//getService definition in -3
Message message = getService().users().messages().get("me", messageId).setFormat("raw").execute();
Base64 base64Url = new Base64(true);
byte[] emailBytes = base64Url.decodeBase64(message.getRaw());
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes));
return getText(email); //getText definition in at -4
}
Run Code Online (Sandbox Code Playgroud)
3- 这是创建 Gmail 实例的部分:
private static Gmail getService() throws Exception {
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
// Load client secrets.
InputStream in = SCFManager.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
Run Code Online (Sandbox Code Playgroud)
4- 这就是你解析 Mime Messages 的方式:
public static String getText(Part p) throws
MessagingException, IOException {
if (p.isMimeType("text/*")) {
String s = (String) p.getContent();
return s;
}
if (p.isMimeType("multipart/alternative")) {
// prefer html text over plain text
Multipart mp = (Multipart) p.getContent();
String text = null;
for (int i = 0; i < mp.getCount(); i++) {
Part bp = mp.getBodyPart(i);
if (bp.isMimeType("text/plain")) {
if (text == null) {
text = getText(bp);
}
continue;
} else if (bp.isMimeType("text/html")) {
String s = getText(bp);
if (s != null) {
return s;
}
} else {
return getText(bp);
}
}
return text;
} else if (p.isMimeType("multipart/*")) {
Multipart mp = (Multipart) p.getContent();
for (int i = 0; i < mp.getCount(); i++) {
String s = getText(mp.getBodyPart(i));
if (s != null) {
return s;
}
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
5- 如果您想知道如何获取电子邮件 ID,您可以通过以下方式列出它们:
public static List<String> listTodayMessageIds() throws Exception {
ListMessagesResponse response = getService()
.users()
.messages()
.list("me")
.execute();
if (response != null && response.getMessages() != null && !response.getMessages().isEmpty()) {
return response.getMessages().stream().map(Message::getId).collect(Collectors.toList());
} else {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
笔记:
如果在此之后您想以“某种 Java 脚本方式”查询该 html 正文,我建议您探索 jsoup 库..非常直观且易于使用:
Document jsoup = Jsoup.parse(body);
Elements tds = jsoup.getElementsByTag("td");
Elements ps = tds.get(0).getElementsByTag("p");
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助 :-)