Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Mail API: send emails via corporate outlook acount [closed]

I want my program to be able to send emails from my corporate outlook account. I looked at many JMA examples the do not seem to be what I want.

  1. Where can I find simple examples of sending mails via outlook?
  2. Should I move mailing system to separate service-application? and if so, why?
like image 613
VB_ Avatar asked Dec 16 '13 14:12

VB_


2 Answers

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);
        }
    }
}
like image 173
Rakshith Avatar answered Sep 28 '22 20:09

Rakshith


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

like image 39
adi Avatar answered Sep 28 '22 21:09

adi