/** Creates the given {@code labelName} in the import service provider and returns the id. */ private String createImportedLabelId(TokensAndUrlAuthData authData, String labelName) throws IOException { Label newLabel = new Label() .setName(labelName) .setLabelListVisibility("labelShow") .setMessageListVisibility("show"); return getOrCreateGmail(authData).users().labels().create(USER, newLabel).execute().getId(); }
@Override public Map<String, String> get() { ListLabelsResponse response = null; try { response = getOrCreateGmail(authData).users().labels().list(USER).execute(); } catch (IOException e) { throw new RuntimeException("Unable to list labels for user", e); } ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (Label label : response.getLabels()) { // TODO: remove system labels builder.put(label.getName(), label.getId()); } return builder.build(); } };
/** * Sets up a response with a single message */ private void setUpSingleMessageResponse() throws IOException { messageListResponse = new ListMessagesResponse() .setMessages(Collections.singletonList(INITIAL_MESSAGE)); when(messageListRequest.execute()).thenReturn(messageListResponse); when(get.execute()).thenReturn(FULL_MESSAGE); } }
List<MailMessageModel> results = new ArrayList<>(response.getMessages().size()); for (Message listMessage : response.getMessages()) { Message getResponse = null; try { getResponse = gmail.users().messages().get(USER, listMessage.getId()).setFormat("raw").execute(); } catch (IOException e) { return new ExportResult<>(e); results.add(new MailMessageModel(getResponse.getRaw(), getResponse.getLabelIds())); if (response.getNextPageToken() != null) { newPage = new StringPaginationToken(response.getNextPageToken()); resultType = ResultType.CONTINUE;
new Message() .setRaw(mailMessageModel.getRawString()) .setLabelIds(importedLabelIds.build()); try { getOrCreateGmail(authData).users().messages().insert(USER, newMessage).execute();
@Override public void onSuccess( ListMessagesResponse response, HttpHeaders responseHeaders) throws IOException { if (!response.isEmpty()) { results.putAll(localMessage, response.getMessages()); System.err.println( "For " + localMessage.getMessageId() + " got:"); response.getMessages().stream().forEach(message -> System.err.println(" message id: " + message.getId())); } } });
@Before public void setUp() throws IOException { Label label = new Label(); label.setId(LABEL1); label.setName(LABEL1); labelsListResponse = new ListLabelsResponse().setLabels(Collections.singletonList(label)); jobStore = new LocalJobStore(); Monitor monitor = new Monitor() {}; googleMailImporter = new GoogleMailImporter(googleCredentialFactory, jobStore, gmail, monitor); when(gmail.users()).thenReturn(users); when(users.messages()).thenReturn(messages); when(messages.insert(Matchers.anyString(), Matchers.any(Message.class))).thenReturn(insert); when(users.labels()).thenReturn(labels); when(labels.list(Matchers.anyString())).thenReturn(labelsList); when(labelsList.execute()).thenReturn(labelsListResponse); when(labels.create(Matchers.anyString(), Matchers.any(Label.class))).thenReturn(labelsCreate); when(labelsCreate.execute()).thenReturn(label); verifyZeroInteractions(googleCredentialFactory); }
private void markMessageAsRead(Message messageStub) throws IOException { ModifyMessageRequest modifyMessageRequest = new ModifyMessageRequest() .setRemoveLabelIds(Collections.singletonList("UNREAD")); service.users().messages().modify(username, messageStub.getId(), modifyMessageRequest).execute(); }
public static boolean sendMessage(String email, String subject, String text) { if (email.isEmpty()) { logger.info("Email is not sent because the address is empty"); return false; } try { Gmail gmail = new Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("XMage Server").build(); MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties())); mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(email)); mimeMessage.setSubject(subject); mimeMessage.setText(text); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mimeMessage.writeTo(baos); Message message = new Message(); message.setRaw(Base64.encodeBase64URLSafeString(baos.toByteArray())); gmail.users().messages().send(ConfigSettings.instance.getGoogleAccount() + (ConfigSettings.instance.getGoogleAccount().endsWith("@gmail.com") ? "" : "@gmail.com"), message).execute(); return true; } catch (MessagingException | IOException ex) { logger.error("Error sending message", ex); } return false; } }
@Override public void onFailure( GoogleJsonError e, HttpHeaders responseHeaders) throws IOException { System.err.format("For message: %s, got error: %s\n", message.getId(), e.toPrettyString()); }
@Test public void importMessage() throws IOException { MailContainerResource resource = new MailContainerResource(null, Collections.singletonList(MESSAGE_MODEL)); ImportResult result = googleMailImporter.importItem(JOB_ID, null, resource); // Getting list of labels from Google verify(labelsList).execute(); // Importing message ArgumentCaptor<Message> messageArgumentCaptor = ArgumentCaptor.forClass(Message.class); verify(messages).insert(eq(GoogleMailImporter.USER), messageArgumentCaptor.capture()); assertThat(messageArgumentCaptor.getValue().getRaw()).isEqualTo(MESSAGE_RAW); // TODO(olsona): test labels } }
/** * Returns an empty list if there is no unread email of the user. */ private List<Message> getListOfUnreadEmailOfUser() throws IOException { List<Message> messageStubs = service.users().messages().list(username).setQ("is:UNREAD").execute().getMessages(); return messageStubs == null ? new ArrayList<>() : messageStubs; }
private String getSender(List<MessagePartHeader> headers){ for(MessagePartHeader header: headers){ if("From".equals(header.getName())){ String sender = header.getValue(); int addressIndex = sender.indexOf('<'); if(addressIndex > 0){ sender = sender.substring(0, addressIndex).trim(); } return sender; } } return "Unknown Gmail Source"; }
@Test public void exportMessagesSubsequentSet() throws IOException { setUpSingleMessageResponse(); // Looking at subsequent page, with no page after it PaginationData paginationData = new StringPaginationToken(NEXT_TOKEN); ExportInformation exportInformation = new ExportInformation(paginationData, null); messageListResponse.setNextPageToken(null); // Run test ExportResult<MailContainerResource> result = googleMailExporter.export(JOB_ID, null, Optional.of(exportInformation)); // Check results // Verify correct calls were made (i.e., token was set before execution) InOrder inOrder = Mockito.inOrder(messageListRequest); inOrder.verify(messageListRequest).setPageToken(NEXT_TOKEN); inOrder.verify(messageListRequest).execute(); // Check pagination token (should be null) ContinuationData continuationData = (ContinuationData) result.getContinuationData(); StringPaginationToken paginationToken = (StringPaginationToken) continuationData.getPaginationData(); assertThat(paginationToken).isNull(); }
@Override public void onSuccess( Message message, HttpHeaders responseHeaders) throws IOException { System.err.println(message.toPrettyString()); } };
@Override public void onFailure( GoogleJsonError e, HttpHeaders responseHeaders) throws IOException { System.err.format("For message: %s, got error: %s\n", message.getId(), e.toPrettyString()); if (e.getCode() == TOO_MANY_CONCURRENT_REQUESTS_FOR_USER) { request.queue(batches.nextBatch, this); } }
private MimeMessage convertFromMessageToMimeMessage(Message message) throws MessagingException { byte[] emailBytes = BaseEncoding.base64Url().decode(message.getRaw()); // While we are not actually sending or receiving an email, a session is required so there will be strict parsing // of address headers when we create a MimeMessage. We are also passing in empty properties where we are expected to // supply some values because we are not actually sending or receiving any email. Session session = Session.getInstance(new Properties()); return new MimeMessage(session, new ByteArrayInputStream(emailBytes)); }
messageListResponse.setNextPageToken(NEXT_TOKEN);
/** * Retrieves the registration key among the unread emails * with {@code courseId} and {@code courseName} sent to the Gmail inbox. * * <p>After retrieving, marks the email as read. * * <p>If multiple emails of the same course are in the inbox, return the registration key presented in one of them. * * @return registration key (null if cannot be found). */ public String getRegistrationKeyFromUnreadEmails(String courseName, String courseId) throws IOException, MessagingException { List<Message> messageStubs = getListOfUnreadEmailOfUser(); for (Message messageStub : messageStubs) { Message message = service.users().messages().get(username, messageStub.getId()).setFormat("raw") .execute(); MimeMessage email = convertFromMessageToMimeMessage(message); if (isStudentCourseJoinRegistrationEmail(email, courseName, courseId)) { String body = getTextFromEmail(email); markMessageAsRead(messageStub); return getKey(body); } } return null; }