Retrieve email/message body in html using Gmail API

前端 未结 3 919
耶瑟儿~
耶瑟儿~ 2020-12-07 21:14

Is there any way to retrieve message body in html form using GMail api ?

I have already gone through the message.get docs. Tried changing the format par

3条回答
  •  我在风中等你
    2020-12-07 21:57

    Here is the full tutorial:

    1- Assuming you already went through all credentials creation here

    2- This is how you retrieve a Mime Message:

     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
        }
    

    3- This is the piece that creates the Gmail instance:

    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();
    }
    

    4- And this is how you parse 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;
        }
    

    5- If you were wondering how to get the email id, this is how you list them:

     public static List 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;
            }
        }
    

    Note:

    If after this you want to query that html body in the "kind of Java Script way", I recommend you to explore jsoup library.. very intuitive and easy to work with:

    Document jsoup = Jsoup.parse(body);
    
    Elements tds = jsoup.getElementsByTag("td");
    Elements ps = tds.get(0).getElementsByTag("p");
    

    I hope this helps :-)

提交回复
热议问题