Reputation: 23104
From Google's official doc, here is how you can create email messages with their 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;
}
So you need a from
field, which leads to the questions: how do you fetch the user's email address?
Upvotes: 1
Views: 745
Reputation: 112787
You can use getProfile to get the email address of the user:
Request
GET https://www.googleapis.com/gmail/v1/users/me/profile?fields=emailAddress&access_token={ACCESS_TOKEN}
Response
{
"emailAddress": "[email protected]"
}
In Java this could look like:
GetProfile profile = service.users().getProfile("me").execute();
System.out.println(profile.getEmailAddress());
Upvotes: 3