How to send TLS gmail, EWS, outlook365 email with java mail API

In my previous post, I’ve given you the code which sends email using Microsoft’s EWS web java API. The example given below does the same task using java mail API. This should work for EWS , outlook 365 and gmail.

o365-logo

package org.grassfield;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMailTLS {
public static void main(String[] args) {
final String username = "pandian@myoutlook365.com";
final String password = "mypassword";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.office365.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("pandian@myoutlook365.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("mygirlfriend@likeverymuch.com"));
message.setSubject("Test TLS Subject");
message.setText("Body of the email");
Transport.send(message);
System.out.println("Sent");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}

Send java mail with Office365 / EWS

This code works with Office 365.

o365-logo

package org.grassfield.mail;
import microsoft.exchange.webservices.data.*;
import java.net.*;
public class Office365Mail {
public static void main(String[] args) throws Exception {
String body = "";
System.setProperty("javax.net.ssl.keyStore","c:\\Program Files\\Java\\jre8\\lib\\security\\cacerts");
String emailAddress = "pandian@grassfield.org";
String password = "chuVuf5u";
String subject = "eGXchgMailTest";
ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials("mail@grassfield.org",password,"grassfield.org");
service.setCredentials(credentials);
service.setUrl(new URI("https://outlook.office365.com/EWS/Exchange.asmx"));
// service.setTraceEnabled(true);
EmailMessage message = new EmailMessage(service);
body = "this is a body message";
message.setSubject(subject);
message.setBody(MessageBody.getMessageBodyFromText(body));
message.setSubject(subject);
message.getToRecipients().add(emailAddress);
message.send();
}
}

Get the EWS mail jars and dependencies from respective websites.