service.users().messages().send("me", m).execute();
@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(); } };
@Before public void setup() throws IOException { googleMailExporter = new GoogleMailExporter(googleCredentialFactory, gmail); when(gmail.users()).thenReturn(users); when(users.messages()).thenReturn(messages); when(messages.list(Matchers.anyString())).thenReturn(messageListRequest); when(messageListRequest.setMaxResults(Matchers.anyLong())).thenReturn(messageListRequest); when(messages.get(Matchers.anyString(), Matchers.anyString())).thenReturn(get); when(get.setFormat(Matchers.anyString())).thenReturn(get); verifyZeroInteractions(googleCredentialFactory); }
@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); }
/** 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(); }
.setLabelIds(importedLabelIds.build()); try { getOrCreateGmail(authData).users().messages().insert(USER, newMessage).execute(); } catch (IOException e) { return new ImportResult(e);
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; } }
/** * 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 void markMessageAsRead(Message messageStub) throws IOException { ModifyMessageRequest modifyMessageRequest = new ModifyMessageRequest() .setRemoveLabelIds(Collections.singletonList("UNREAD")); service.users().messages().modify(username, messageStub.getId(), modifyMessageRequest).execute(); }
List<String> labels = new ArrayList<String>(); ListLabelsResponse listResponse = service.users().labels().list(userId).execute(); for (Label label : listResponse.getLabels()) { Label countLabel = service.users().labels().get(userId, label.getId()).execute(); if (countLabel.getName().equalsIgnoreCase("UNREAD")) unreadId = countLabel.getId(); } List<String> add = new ArrayList<String>(); List<String> remove = new ArrayList<String>(); remove.add(unreadId); modifyMessage(service, userId, message.getId(), add, remove); public static void modifyMessage(Gmail service, String userId, String messageId, List<String> labelsToAdd, List<String> labelsToRemove) throws IOException { ModifyMessageRequest mods = new ModifyMessageRequest().setAddLabelIds(labelsToAdd) .setRemoveLabelIds(labelsToRemove); Message message = service.users().messages().modify(userId, messageId, mods).execute(); }
/** * Send an email from the user's mailbox to its recipient. * * @param service Authorized Gmail API instance. * @param userId User's email address. The special value "me" * can be used to indicate the authenticated user. * @param email Email to be sent. * @throws MessagingException * @throws IOException */ public static void sendMessage(Gmail service, String userId, MimeMessage email) throws MessagingException, IOException { Message message = createMessageWithEmail(email); message = service.users().messages().send(userId, message).execute(); System.out.println("Message id: " + message.getId()); System.out.println(message.toPrettyString()); }
/** * 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; }
public List<Message> listAllMessages(Gmail service, String userId ) throws IOException { ListMessagesResponse response = service.users().messages().list(userId).execute(); if (response == null || response.isEmpty()) return null; List<Message> messages = new ArrayList<Message>(); messages.addAll(response.getMessages()); int totalMsgs = messages.size(); Message message; if (totalMsgs > 0) { for (int i = 0; i < totalMsgs; i++) { message = messages.get(i); //message.getId() is what you want } } return messages; }
/** * Loads the user's labels and remembers them. */ void loadLabels() throws IOException { ListLabelsResponse labelResponse = gmailService.getServiceWithRetries() .users() .labels() .list(user.getEmailAddress()) .execute(); Verify.verify(!labelResponse.isEmpty(), "could not get labels %s"); List<Label> labels = labelResponse.getLabels(); labelsByName = labels.stream().collect(toMap(Label::getName, label -> label)); labelsById = labels.stream().collect(toMap(Label::getId, label -> label)); System.err.format("Got labels: %s", labelsByName); }
for (String label : missingLabels) { System.err.format("Adding label %s\n", label); gmailApi.users() .labels() .create(user.getEmailAddress(), new Label()
@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()); } }
public static void main(String... args) throws IOException, GeneralSecurityException { // Build a new authorized API client service. final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) .setApplicationName(APPLICATION_NAME) .build(); // Print the labels in the user's account. String user = "me"; ListLabelsResponse listResponse = service.users().labels().list(user).execute(); List<Label> labels = listResponse.getLabels(); if (labels.isEmpty()) { System.out.println("No labels found."); } else { System.out.println("Labels:"); for (Label label : labels) { System.out.printf("- %s\n", label.getName()); } } } }
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; }
gmail.users().messages().get(user.getEmailAddress(), message.getId()) .setFields("id,labelIds") .queue(batch, new JsonBatchCallback<Message>() {