Thursday, February 5, 2015

How to Send Email using Office 365 from your application

//email.properties
 mail.smtp.host=smtp.office365.com  
 mail.smtp.port=587  
 mail.smtp.starttls.enable=true  
 mail.smtp.auth=true  
 mail.smtp.ssl.trust=smtp.office365.com  
 mail.user=noreply@mycompany.com  
 mail.password=Password123$  

//Your Java Controller
 Properties properties = new Properties();  
 properties.load(getClass().getClassLoader().getResourceAsStream("email.properties"));  
 Session mailSession = null;  
 try{  
 final String emailUserNm = properties.getProperty("mail.user");  
 final String emailPassword = properties.getProperty("mail.password");  
 mailSession = Session.getInstance(properties,  
      new javax.mail.Authenticator() {  
           protected PasswordAuthentication getPasswordAuthentication() {  
           return new PasswordAuthentication(emailUserNm, emailPassword);  
      }  
 });  
 }catch(Exception e){  
      System.out.println("hello");  
 }  
 String from = properties.getProperty("mail.user");   

Some Notes:

  • Username and From field of the email should be the same email. 
  • Office 365 is using TLS authentication.

No comments:

Post a Comment