How do I set up outbound SMTP using JavaMail?


How do I set up outbound SMTP using JavaMail?


The following example of code shows you how to send an email using outMail as the SMTP SmartHost mail relay using the JavaMail for Java.

outMail is an authenticated SMTP relay so the example below shows authentication in Java as well. The code below uses the default SMTP port 25 but it can easily be changed to an alternative SMTP port by editing the variable hostPort in the code below.

Example code

import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;

public class SmtpTest {
	public static void main(String[] args) {
		// outMail login Details
		final String outmailUsername = "outmail-username";
		final String outmailPassword = "outmail-password";

		// Recipient's Email Address
		String toEmail            = "";
		// Sender's Email Address
		String fromEmail          = ""; 
		String fromEmailName      = "Firstname Lastname"; 
		// Set the email properties
		Properties props = new Properties();
		props.put("", "");	// SMTP Host
		props.put("mail.smtp.port", "25"); 							// SMTP Port
		props.put("mail.smtp.auth", "true"); 						// SMTP Authentication Enabled
		// Create an authenticator object 
		Authenticator auth = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(outmailUsername, outmailPassword);
		Session session = Session.getInstance(props, auth);
			MimeMessage msg = new MimeMessage(session);
			msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
			msg.addHeader("Content-Transfer-Encoding", "8bit");
			msg.setSentDate(new Date());

			msg.setFrom(new InternetAddress(fromEmail, fromEmailName));
			msg.setReplyTo(InternetAddress.parse(fromEmail, false));

			msg.setSubject("Subject of the email goes here", "UTF-8");

			msg.setText("Body of the message goes here", "UTF-8");
			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));

	    catch (Exception e) {

Summary of server details

Outgoing server

As provided in your signup email.

Outgoing server protocol


Outgoing server port

25, 587, 2525 or 8025

Authentication Type

Basic Authentication


As provided


As provided

(0 vote(s))
Not helpful

The Origin of this information may be internal or external to Prolateral Consulting Ltd. Prolateral makes all reasonable efforts to verify this information. However, the information provided in this document is for your information only. Prolateral makes no explicit or implied claims to the validity of this information. Any trademarks referenced in this document are the property of their respective owners.