Java Mail API: send emails via corporate outlook acount

You need to download javax.mail JAR first. Then try the following code:

import java.io.IOException;
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 SendMail {

    public static void main(String[]args) throws IOException {

        final String username = "enter your username";
        final String password = "enter your password";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "outlook.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("enter your outlook mail address"));
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse("Enter the recipient mail address"));
            message.setSubject("Test");
            message.setText("HI");

            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

All you need is your SMTP settings for your corporate account. Set these in your program using Java mail API and thats it. e.g.

Properties props = System.getProperties();
props.put("mail.smtp.host", "your server here");
Session session = Session.getDefaultInstance(props, null);

example: here and here


I tried with outlook.office365.com as a host name and got authentication unaccepted exception. When trying with smtp-mail.outlook.com I'm able to send mails through outlook with Javamail API.

For further detail Check out the settings of Outlook on outlook official site.

For complete working demo code Read this answer.