【问题标题】:how do you fetch gmail user's email address using gmail java api?您如何使用 gmail java api 获取 gmail 用户的电子邮件地址?
【发布时间】:2016-07-30 20:03:58
【问题描述】:

来自Google's official doc,您可以通过以下方式使用他们的 java api 创建电子邮件:

  public static MimeMessage createEmail(String to, String from, String subject,
      String bodyText) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session);
    InternetAddress tAddress = new InternetAddress(to);
    InternetAddress fAddress = new InternetAddress(from);

    email.setFrom(new InternetAddress(from));
    email.addRecipient(javax.mail.Message.RecipientType.TO,
                       new InternetAddress(to));
    email.setSubject(subject);
    email.setText(bodyText);
    return email;
  }

/**
   * Create a Message from an email
   *
   * @param email Email to be set to raw of message
   * @return Message containing base64url encoded email.
   * @throws IOException
   * @throws MessagingException
   */
  public static Message createMessageWithEmail(MimeMessage email)
      throws MessagingException, IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    email.writeTo(bytes);
    String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
    Message message = new Message();
    message.setRaw(encodedEmail);
    return message;
  }

所以您需要一个from 字段,这会导致以下问题:您如何获取用户的电子邮件地址?

【问题讨论】:

  • 哪个用户?从什么获取?
  • 应用程序代表其处理邮件的用户。
  • 我想来自一些谷歌数据库?

标签: java gmail-api


【解决方案1】:

您可以使用getProfile获取用户的电子邮件地址:

请求

GET https://www.googleapis.com/gmail/v1/users/me/profile?fields=emailAddress&access_token={ACCESS_TOKEN}

回应

{
 "emailAddress": "foo@example.com"
}

在 Java 中可能如下所示:

GetProfile profile = service.users().getProfile("me").execute();
System.out.println(profile.getEmailAddress());

【讨论】:

    猜你喜欢
    • 2015-01-13
    • 2023-03-14
    • 1970-01-01
    • 2015-07-15
    • 2018-11-03
    • 2020-09-04
    • 1970-01-01
    • 2019-01-22
    • 2017-01-11
    相关资源
    最近更新 更多