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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With