Spring Email using Office 365

I’m using javamail package in raw format so far. I prefer to split all the communications (email, social media…) and run it as a spring REST API server. Here is the initial code snippet.

Take STS or Eclipse, Start a Spring Starter Project and follow the instructions given below.

Dependencies

Maven Dependencies are given below.

4.0.0

org.springframework.boot
spring-boot-starter-parent
2.1.8.RELEASE

org.grassfield
messenger
0.0.1-SNAPSHOT
messenger
MultiPlatformMessenger

1.8
UTF-8
UTF-8

org.springframework.boot
spring-boot-starter-mail

org.springframework.boot
spring-boot-starter-web

org.springframework.boot
spring-boot-starter-test
test

org.springframework.boot
spring-boot-maven-plugin

User.java

This is an entity class for the user.


package org.grassfield.msg;

import org.springframework.stereotype.Component;

/**
* The Class User.
* @author Murugapandian Ramaiah
* @version 1.0
*/
@Component
public class User {
private String email;

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

}

 

 

MailService.java

As the name implies this is the email sending service.


package org.grassfield.msg;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
public class MailService {
@Autowired
private JavaMailSender sender;

public void sendEmail (User user) {
SimpleMailMessage mail = new SimpleMailMessage();
mail.setFrom(user.getEmail());
mail.setTo(user.getEmail());
mail.setSubject("Testing Email Service");
mail.setText("Test email content");
this.sender.send(mail);
}

public void sendEmailWithAttachment(User user) throws MessagingException, UnsupportedEncodingException {
MimeMessage mimeMsg = this.sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, true);
helper.setFrom(new InternetAddress(user.getEmail(), user.getEmail()));
helper.setTo(user.getEmail());
helper.setSubject("Multipart email");
helper.setText("Content of this email");
this.sender.send(mimeMsg);
}

}

 

 

MailController.java

Here is the REST controller.


package org.grassfield.msg;

import java.io.UnsupportedEncodingException;

import javax.mail.MessagingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* The Class MailController.
* @author Murugapandian Ramaiah
* @version 1.0
*/
@RestController
public class MailController {

/** The service. */
@Autowired
private MailService service;

/** The user. */
@Autowired
private User user;

@RequestMapping("test-plain-text-email")
public String testPlainTextEmail() {
user.setEmail("recipient@office365 email address");
service.sendEmail(user);
return "Email sent";
}

@RequestMapping("test-multipart-email")
public String testMultipartEmail() throws MessagingException, UnsupportedEncodingException {
user.setEmail("recipient@office365 email address");
service.sendEmailWithAttachment(user);
return "Email sent";
}

}

 

 

application.properties


spring.mail.host = smtp.office365.com
spring.mail.username = user@office 365 account
spring.mail.password = office 365 password
spring.mail.port=587
spring.mail.properties.mail.smtp.port=587
spring.mail.properties.mail.transport.protocol=smtps
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=false
spring.mail.properties.mail.smtp.timeout=15000
spring.mail.properties.mail.smtp.connectiontimeout=15000
spring.mail.properties.mail.smtp.socketFactory.fallback = true
spring.mail.properties.mail.mail.debug=true
spring.mail.properties.mail.pop3.host=pop email address
spring.mail.properties.mail.pop3.port=110
spring.mail.properties.mail.pop3.starttls.enable=true
spring.mail.properties.mail.pop3.store=pop3s
spring.mail.properties.pop.pop3.username=pop username
spring.mail.properties.pop.pop3.password=pop password
spring.mail.properties.pop.pop3.folder=INBOX

 

 

Test

Test your services with these.

curl -X GET -i http://localhost:8080/test-plain-text-email

curl -X GET -i http://localhost:8080/test-multipart-email

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.