com.google.api.services.gmail.model.Message Java Examples

The following examples show how to use com.google.api.services.gmail.model.Message. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GoogleMailResource.java    From camel-quarkus with Apache License 2.0 7 votes vote down vote up
@Path("/read")
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response readMail(@QueryParam("messageId") String messageId) {
    Map<String, Object> headers = new HashMap<>();
    headers.put("CamelGoogleMail.userId", USER_ID);
    headers.put("CamelGoogleMail.id", messageId);

    try {
        Message response = producerTemplate.requestBodyAndHeaders("google-mail://messages/get", null, headers,
                Message.class);
        if (response != null && response.getPayload() != null) {
            String body = new String(response.getPayload().getBody().decodeData(), StandardCharsets.UTF_8);
            return Response.ok(body).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    } catch (CamelExecutionException e) {
        Exception exchangeException = e.getExchange().getException();
        if (exchangeException != null && exchangeException.getCause() instanceof GoogleJsonResponseException) {
            GoogleJsonResponseException originalException = (GoogleJsonResponseException) exchangeException.getCause();
            return Response.status(originalException.getStatusCode()).build();
        }
        throw e;
    }
}
 
Example #2
Source File: GoogleMailResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
private Message createMessage(String body) throws MessagingException, IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);

    Profile profile = producerTemplate.requestBody("google-mail://users/getProfile?inBody=userId", USER_ID, Profile.class);
    MimeMessage mm = new MimeMessage(session);
    mm.addRecipients(TO, profile.getEmailAddress());
    mm.setSubject(EMAIL_SUBJECT);
    mm.setContent(body, "text/plain");

    Message message = new Message();
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        mm.writeTo(baos);
        message.setRaw(Base64.getUrlEncoder().encodeToString(baos.toByteArray()));
    }
    return message;
}
 
Example #3
Source File: GoogleMailResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Path("/create")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response createMail(String message) throws Exception {
    Message email = createMessage(message);
    Map<String, Object> headers = new HashMap<>();
    headers.put("CamelGoogleMail.userId", USER_ID);
    headers.put("CamelGoogleMail.content", email);
    final Message response = producerTemplate.requestBodyAndHeaders("google-mail://messages/send", null, headers,
            Message.class);
    return Response
            .created(new URI("https://camel.apache.org/"))
            .entity(response.getId())
            .build();
}
 
Example #4
Source File: GoogleMailImporterTest.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  Label label = new Label();
  label.setId(LABEL1);
  label.setName(LABEL1);
  labelsListResponse = new ListLabelsResponse().setLabels(Collections.singletonList(label));

  Monitor monitor = new Monitor() {};
  googleMailImporter = new GoogleMailImporter(googleCredentialFactory, gmail, monitor);
  executor = new FakeIdempotentImportExecutor();

  when(gmail.users()).thenReturn(users);
  when(users.messages()).thenReturn(messages);
  when(messages.insert(anyString(), any(Message.class))).thenReturn(insert);
  when(insert.execute()).thenReturn(new Message().setId("fooBar"));
  when(users.labels()).thenReturn(labels);
  when(labels.list(anyString())).thenReturn(labelsList);
  when(labelsList.execute()).thenReturn(labelsListResponse);
  when(labels.create(anyString(), any(Label.class))).thenReturn(labelsCreate);
  when(labelsCreate.execute()).thenReturn(label);

  verifyNoInteractions(googleCredentialFactory);
}
 
Example #5
Source File: GoogleMailIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
private static Message createMessage(ProducerTemplate template, String subject)
        throws MessagingException, IOException {

    Profile profile = template.requestBody("google-mail://users/getProfile?inBody=userId", CURRENT_USERID,
            Profile.class);
    Session session = Session.getDefaultInstance(new Properties(), null);
    MimeMessage mm = new MimeMessage(session);
    mm.addRecipients(javax.mail.Message.RecipientType.TO, profile.getEmailAddress());
    mm.setSubject(subject);
    mm.setContent("Camel rocks!\n" //
            + DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()) + "\n" //
            + "user: " + System.getProperty("user.name"), "text/plain");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mm.writeTo(baos);
    String encodedEmail = Base64.getUrlEncoder().encodeToString(baos.toByteArray());
    Message message = new Message();
    message.setRaw(encodedEmail);
    return message;
}
 
Example #6
Source File: SendMailWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public Message sendMessage(Gmail service,
                           String to,
                           String from,
                           String subject,
                           String bodyText,
                           Document attachment)
        throws MessagingException, IOException {
    MimeMessage mimeMessage = createEmailWithAttachment(to,
                                                        from,
                                                        subject,
                                                        bodyText,
                                                        attachment);
    Message message = service.users().messages().send(from,
                                                      createMessageWithEmail(mimeMessage)).execute();

    return message;
}
 
Example #7
Source File: EmailAccount.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #8
Source File: GmailSyncer.java    From mail-importer with Apache License 2.0 6 votes vote down vote up
/**
 * Synchronizes the given list of messages with Gmail. When this operation
 * completes, all of the messages will appear in Gmail with the same labels
 * (folers) that they have in the local store. The message state, including
 * read/unread, will also be synchronized, but might not match exactly if
 * the message is already in Gmail.
 *
 * <p>Note that some errors can prevent some messages from being uploaded.
 * In this case, the failure policy dictates what happens.
 *
 * @param messages the list of messages to synchronize. These messages may
 *     or may not already exist in Gmail.
 * @throws IOException if something goes wrong with the connection
 */
public void sync(List<LocalMessage> messages) throws IOException {
  Preconditions.checkState(initialized,
      "GmailSyncer.init() must be called first");
  Multimap<LocalMessage, Message> map = mailbox.mapMessageIds(messages);
  messages.stream()
      .filter(message -> !map.containsKey(message))
      .forEach(message -> {
        try {
          Message gmailMessage = mailbox.uploadMessage(message);
          map.put(message, gmailMessage);
        } catch (GoogleJsonResponseException e) {
          // Message couldn't be uploaded, but we know why
        }
      });
  mailbox.fetchExistingLabels(map.values());
  mailbox.syncLocalLabelsToGmail(map);
}
 
Example #9
Source File: GoogleMailIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private static boolean idInList(String testEmailId, ListMessagesResponse listOfMessages) {
    Assert.assertNotNull("list result", listOfMessages);
    List<Message> messages = listOfMessages.getMessages();
    if (messages != null) {
        for (Message m : listOfMessages.getMessages()) {
            if (testEmailId.equals(m.getId())) {
                return true;
            }
        }
    }
    return false;
}
 
Example #10
Source File: EmailAccount.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
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));
}
 
Example #11
Source File: EmailAccount.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Marks all unread emails in the user's inbox as read.
 */
public void markAllUnreadEmailAsRead() throws IOException {
    List<Message> messageStubs = getListOfUnreadEmailOfUser();

    for (Message messageStub : messageStubs) {
        markMessageAsRead(messageStub);
    }
}
 
Example #12
Source File: GoogleMailWorkitemHandlerTest.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    try {
        when(auth.getGmailService(anyString(),
                                  anyString())).thenReturn(gmailService);
        when(gmailService.users()).thenReturn(gmailUsers);
        when(gmailUsers.messages()).thenReturn(gmailUserMessages);
        when(gmailUserMessages.send(anyString(),
                                    anyObject())).thenReturn(gmailUserMessagesSend);
        when(gmailUserMessagesSend.execute()).thenReturn(new Message());
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
 
Example #13
Source File: SendMailWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public static Message createMessageWithEmail(MimeMessage emailContent)
        throws MessagingException, IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    emailContent.writeTo(buffer);
    byte[] bytes = buffer.toByteArray();
    String encodedEmail = Base64.encodeBase64URLSafeString(bytes);
    Message message = new Message();
    message.setRaw(encodedEmail);
    return message;
}
 
Example #14
Source File: SendMailWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {
    String paramTo = (String) workItem.getParameter("To");
    String paramFrom = (String) workItem.getParameter("From");
    String paramSubject = (String) workItem.getParameter("Subject");
    String paramBodyText = (String) workItem.getParameter("BodyText");
    Document paramAttachment = (Document) workItem.getParameter("Attachment");

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        Gmail gmailService = auth.getGmailService(appName,
                                                  clientSecret);
        Message outEmailMessage = sendMessage(gmailService,
                                              paramTo,
                                              paramFrom,
                                              paramSubject,
                                              paramBodyText,
                                              paramAttachment);

        workItemManager.completeWorkItem(workItem.getId(),
                                         outEmailMessage);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example #15
Source File: BaseGmailProvider.java    From PrivacyStreams with Apache License 2.0 5 votes vote down vote up
private List<String> getDataFromApi(String query) throws IOException {
    List<String> messageList = new ArrayList<>();
    String user = "me";
    ListMessagesResponse response = mService.users().messages().list(user).setQ(query).execute();
    int total = 1;
    String deliverTo = "";
    String from = "";
    String subject = "";
    String content = "";
    long timestamp = 0;
    if (response.getMessages() != null) {
        for(int i = response.getMessages().size()-1;i>=0;i--){
            Message item = response.getMessages().get(i);
            if (total > mMaxResult) {
                break;
            }
            Message message = mService.users().messages().get(user, item.getId()).setFormat("full").execute();
            List<MessagePart> messageParts = message.getPayload().getParts();
            List<MessagePartHeader> headers = message.getPayload().getHeaders();

            if (!headers.isEmpty()) {
                for (MessagePartHeader header : headers) {
                    String name = header.getName();
                    switch (name) {
                        case "From":
                            from = header.getValue();
                            break;
                        case "To":
                            deliverTo = header.getValue();
                            break;
                        case "Subject":
                            subject = header.getValue();
                            break;
                        case "Date":
                            String date = header.getValue();
                            if(date.contains(","))
                                date = date.substring(date.indexOf(",") + 2,date.length());;
                            String timestampFormat = "dd MMM yyyy HH:mm:ss Z";
                            timestamp = TimeUtils.fromFormattedString(timestampFormat,date) / 1000;
                            break;
                    }
                }
            }
            if (messageParts != null && !messageParts.isEmpty()) {
                byte[] bytes = Base64.decodeBase64(messageParts.get(0).getBody().getData());
                if (bytes != null) {
                    String mailText = new String(bytes);
                    if (!mailText.isEmpty()) {
                        total++;
                        content = mailText;
                        messageList.add(mailText);
                    }
                }
            }
            if(mLastEmailTime < timestamp) mLastEmailTime = timestamp;
            this.output(new Email(content, AppUtils.APP_PACKAGE_GMAIL, from, deliverTo, subject, timestamp));
        }
    }

    //Reset the value for from and to
    mBegin = 0;
    mEnd = 0;
    return messageList;
}
 
Example #16
Source File: GoogleMailImporterTest.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
@Test
public void importMessage() throws Exception {
  MailContainerResource resource =
      new MailContainerResource(null, Collections.singletonList(MESSAGE_MODEL));

  ImportResult result = googleMailImporter.importItem(JOB_ID, executor, null, resource);

  // Getting list of labels from Google
  verify(labelsList, atLeastOnce()).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
}
 
Example #17
Source File: GoogleMailImporter.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
/**
 * Import each message in {@code messages} into the import account with it's associated labels.
 */
private void importMessages(
    TokensAndUrlAuthData authData,
    IdempotentImportExecutor idempotentExecutor,
    Collection<MailMessageModel> messages) throws Exception {
  for (MailMessageModel mailMessageModel : messages) {
    idempotentExecutor.executeAndSwallowIOExceptions(
        mailMessageModel.toString(),
        // Trim the full mail message to try to give some context to the user but not overwhelm
        // them.
        "Mail message: " + mailMessageModel.getRawString()
            .substring(0, Math.min(50, mailMessageModel.getRawString().length())),
        () -> {
          // Gather the label ids that will be associated with this message
          ImmutableList.Builder<String> importedLabelIds = ImmutableList.builder();
          for (String exportedLabelIdOrName : mailMessageModel.getContainerIds()) {
            // By this time all the label ids have been added to tempdata
            String importedLabelId = idempotentExecutor.getCachedValue(exportedLabelIdOrName);
            if (importedLabelId != null) {
              importedLabelIds.add(exportedLabelIdOrName);
            } else {
              // TODO remove after testing
              monitor.debug(
                  () -> "labels should have been added prior to importing messages");
            }
          }
          // Create the message to import
          Message newMessage =
              new Message()
                  .setRaw(mailMessageModel.getRawString())
                  .setLabelIds(importedLabelIds.build());
          return getOrCreateGmail(authData)
              .users()
              .messages()
              .insert(USER, newMessage)
              .execute()
              .getId();
        });
  }
}
 
Example #18
Source File: GmailDownloader.java    From shortyz with GNU General Public License v3.0 4 votes vote down vote up
@Override
public File download(Date date) {
    LOGGER.fine("==starting gmail download....");
    try {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);
        Date after = calendar.getTime();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 1);
        Date before = calendar.getTime();
        String query = "after:"+dateFormat.format(after)+" AND before:"+dateFormat.format(before)+" AND has:attachment AND (filename:.puz OR filename:.jpz)";
        LOGGER.info("Running query: "+query);
        ListMessagesResponse response = gmailService.users()
                .messages()
                .list("me")
                .setQ(query)
                .execute();
        LOGGER.fine("==Found "+ neverNull(response.getMessages()).size()+" messages.");
        for(Message message : neverNull(response.getMessages())){
            String singleFilename = "";

            Message fetched = gmailService.users().messages().get("me", message.getId())
                    .execute();
            LOGGER.fine("==Fetched message "+fetched.getId());
            HashMap<String, MessagePart> toDownload = new HashMap<>();
            scanParts(fetched.getPayload().getParts(), toDownload);
            for(Map.Entry<String, MessagePart> entry : toDownload.entrySet()){
                LOGGER.info("==Reading : "+singleFilename);
                String source = getSender(fetched.getPayload().getHeaders());
                @SuppressWarnings("deprecation") String filename = (date.getYear() + 1900) + "-" + (date.getMonth() + 1) + "-" + date.getDate() + "-" +
                        source+"-"+singleFilename.replaceAll(" ", "") + ".puz";
                File destination = new File(CROSSWORDS, filename);
                if(!destination.exists()){
                    byte[] data = entry.getValue().getBody().getAttachmentId() != null ?
                            gmailService.users().messages().attachments().get("me", message.getId(), entry.getValue().getBody().getAttachmentId()).execute().decodeData()
                            : entry.getValue().getBody().decodeData();
                    Puzzle puzzle = singleFilename.endsWith("jpz") ?
                            JPZIO.readPuzzle(new ByteArrayInputStream(data))
                            : IO.loadNative(new DataInputStream(new ByteArrayInputStream(data)));
                    puzzle.setDate(date);
                    puzzle.setSource(source);
                    puzzle.setSourceUrl("gmail://" + fetched.getId());
                    puzzle.setUpdatable(false);
                    date = getSentDate(fetched.getPayload().getHeaders());
                    LOGGER.info("Downloaded "+filename);
                    IO.save(puzzle, destination);
                }
            }


        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #19
Source File: EmailAccount.java    From teammates with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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;
}
 
Example #20
Source File: EmailAccount.java    From teammates with GNU General Public License v2.0 4 votes vote down vote up
private void markMessageAsRead(Message messageStub) throws IOException {
    ModifyMessageRequest modifyMessageRequest = new ModifyMessageRequest()
            .setRemoveLabelIds(Collections.singletonList("UNREAD"));
    service.users().messages().modify(username, messageStub.getId(), modifyMessageRequest).execute();
}