2016-04-09 131 views
1

Google's official doc,這裏是你如何可以與他們的Java API創建的電子郵件:如何使用gmail java api獲取gmail用戶的電子郵件地址?

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場,這導致了問題:你如何獲取用戶的電子郵件地址?

+0

哪位用戶?從哪裏獲取? –

+0

用戶代表應用程序處理郵件的人。 – qed

+0

從一些谷歌數據庫,我想? – qed

回答

3

您可以使用getProfile來獲取用戶的電子郵件地址:

請求

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

響應

{ 
"emailAddress": "[email protected]" 
} 

在Java中,這可能是這樣的:

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