DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Authenticate With SMTP Server Before Sending Email

  • submit to reddit
        For more info see:

You need activation.jar, smtp.jar, and mailapi.jar in your classpath for this to work.

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;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailWithPasswordAuthentication {
	public static void main(String[] args) throws MessagingException {
		new MailWithPasswordAuthentication().run();

	private void run() throws MessagingException {
		Message message = new MimeMessage(getSession());

		message.addRecipient(RecipientType.TO, new InternetAddress(""));
		message.addFrom(new InternetAddress[] { new InternetAddress("") });

		message.setSubject("the subject");
		message.setContent("the body", "text/plain");


	private Session getSession() {
		Authenticator authenticator = new Authenticator();

		Properties properties = new Properties();
		properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
		properties.setProperty("mail.smtp.auth", "true");

		properties.setProperty("", "");
		properties.setProperty("mail.smtp.port", "25");

		return Session.getInstance(properties, authenticator);

	private class Authenticator extends javax.mail.Authenticator {
		private PasswordAuthentication authentication;

		public Authenticator() {
			String username = "auth-user";
			String password = "auth-password";
			authentication = new PasswordAuthentication(username, password);

		protected PasswordAuthentication getPasswordAuthentication() {
			return authentication;


Snippets Manager replied on Sat, 2011/06/04 - 6:24am

Thanks it works for me...!!

Snippets Manager replied on Wed, 2009/03/11 - 6:44am

Hello, It doesn´t work for authentication for Exchange 2007. Try username username@domain or domain\\username (escaped slash).