com.google.api.services.gmail.Gmail.users()方法的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(10.8k)|赞(0)|评价(0)|浏览(259)

本文整理了Java中com.google.api.services.gmail.Gmail.users()方法的一些代码示例,展示了Gmail.users()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Gmail.users()方法的具体详情如下:
包路径:com.google.api.services.gmail.Gmail
类名称:Gmail
方法名:users

Gmail.users介绍

[英]An accessor for creating requests from the Users collection.

The typical use is:

Gmail gmail = new Gmail(...); Gmail.Users.List request = gmail.users().list(parameters ...)

[中]用于从Users集合创建请求的访问器。
典型用途是:

Gmail gmail = new Gmail(...); Gmail.Users.List request = gmail.users().list(parameters ...)

代码示例

代码示例来源:origin: stackoverflow.com

service.users().messages().send("me", m).execute();

代码示例来源:origin: google/data-transfer-project

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

代码示例来源:origin: google/data-transfer-project

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

代码示例来源:origin: google/data-transfer-project

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

代码示例来源:origin: google/data-transfer-project

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

代码示例来源:origin: google/data-transfer-project

.setLabelIds(importedLabelIds.build());
try {
 getOrCreateGmail(authData).users().messages().insert(USER, newMessage).execute();
} catch (IOException e) {
 return new ImportResult(e);

代码示例来源:origin: google/data-transfer-project

request = gmail.users().messages().list(USER).setMaxResults(PAGE_SIZE);
} catch (IOException e) {
 return new ExportResult<>(e);
 try {
  getResponse =
    gmail.users().messages().get(USER, listMessage.getId()).setFormat("raw").execute();
 } catch (IOException e) {
  return new ExportResult<>(e);

代码示例来源:origin: magefree/mage

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

代码示例来源:origin: TEAMMATES/teammates

/**
 * 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;
}

代码示例来源:origin: TEAMMATES/teammates

private void markMessageAsRead(Message messageStub) throws IOException {
  ModifyMessageRequest modifyMessageRequest = new ModifyMessageRequest()
      .setRemoveLabelIds(Collections.singletonList("UNREAD"));
  service.users().messages().modify(username, messageStub.getId(), modifyMessageRequest).execute();
}

代码示例来源:origin: stackoverflow.com

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

代码示例来源:origin: stackoverflow.com

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

代码示例来源:origin: TEAMMATES/teammates

/**
 * 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;
}

代码示例来源:origin: stackoverflow.com

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

代码示例来源:origin: google/mail-importer

/**
 * 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);
}

代码示例来源:origin: google/mail-importer

for (String label : missingLabels) {
 System.err.format("Adding label %s\n", label);
 gmailApi.users()
   .labels()
   .create(user.getEmailAddress(), new Label()

代码示例来源:origin: org.jbpm.contrib/google-mail-workitem

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

代码示例来源:origin: gsuitedevs/java-samples

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

代码示例来源:origin: org.jbpm.contrib/google-mail-workitem

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

代码示例来源:origin: google/mail-importer

gmail.users().messages().get(user.getEmailAddress(), message.getId())
  .setFields("id,labelIds")
  .queue(batch, new JsonBatchCallback<Message>() {

相关文章

Gmail类方法