Reputation: 103
The JavaMail way of sending emails through the Gmail SMTP is no longer applicable because of the OAuth2.0 protocol. I can't send emails from my own Google account because there will be authentication issues.
I do have the Gmail API set up with the OAuth2.0, but I realized that this would require the user to log in with their own Google account. I want to send them emails through the Google account that I have specifically set up and not using their own account.
Is this possible?
This is what I have currently.
GmailQuickStart
/** Application name. */
private static final String APPLICATION_NAME =
"Gmail API Java Quickstart";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
".credentials/gmail-java-quickstart");
/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY =
JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
/** Global instance of the scopes required by this quick start. */
private static final List<String> SCOPES =
Arrays.asList(GmailScopes.GMAIL_COMPOSE);
static {
try {
HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
} catch (Throwable t) {
t.printStackTrace();
System.exit(1);
}
}
/**
* Creates an authorized Credential object.
* @return an authorized Credential object.
* @throws IOException
*/
public static Credential authorize() throws IOException {
// Load client secrets.
InputStream in =
GmailQuickstart.class.getResourceAsStream("/project/update/client_secret.json");
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(DATA_STORE_FACTORY)
.setAccessType("offline")
.build();
Credential credential = new AuthorizationCodeInstalledApp(
flow, new LocalServerReceiver()).authorize("user");
System.out.println(
"Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
return credential;
}
/**
* Build and return an authorized Gmail client service.
* @return an authorized Gmail client service
* @throws IOException
*/
public static Gmail getGmailService() throws IOException {
Credential credential = authorize();
return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
.setApplicationName(APPLICATION_NAME)
.build();
}
SendGmail
public static void main (String[] args) {
String to = "Recipient Email";
String from = "Sender Email";
String subject = "Hello World";
String bodyText = "This is an automated message.";
try {
MimeMessage msg = createEmail(to, from, subject, bodyText);
GmailQuickstart gqs = new GmailQuickstart();
Gmail service = gqs.getGmailService();
sendMessage(service, "me", msg);
} catch (MessagingException ex) {
Logger.getLogger(SendGmail.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(SendGmail.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Create a MimeMessage using the parameters provided.
*
* @param to Email address of the receiver.
* @param from Email address of the sender, the mailbox account.
* @param subject Subject of the email.
* @param bodyText Body text of the email.
* @return MimeMessage to be used to send email.
* @throws MessagingException
*/
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;
}
/**
* 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());
}
Upvotes: 2
Views: 3405
Reputation: 4096
I have done this in gmail. Why cant we do this waySample Code. Only thing you need to do is enable less secure app setting in gmail security settings less secure app
Upvotes: 2