In this post, you will learn how to write Java code for sending plain text emails programmatically using JavaMail API.

First, you need to use JavaMail jar files. If you use Maven, add the following dependency to the pom.xml file:

This will add the javax.mail-VERSION.jar and activation-VERSION.jar to the project's classpath. If you have to add them manually, download from JavaMail Project page.

To send an e-mail in plain text using JavaMail, simply call the method setText(String)on the Message object. The following class, PlainTextEmailSender, implements a general method which sends a plain text e-mail message from a SMTP server. It requires supplying information of the SMTP server and the message:

  •             For SMTP server: host, port number, user name (e-mail address), and password.
  •             For e-mail message: recipient address, subject, and message.

Here is the code:

package net.codejava.mail;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class PlainTextEmailSender {

	public void sendPlainTextEmail(String host, String port,
			final String userName, final String password, String toAddress,
			String subject, String message) throws AddressException,
			MessagingException {

		// sets SMTP server properties
		Properties properties = new Properties();
		properties.put("mail.smtp.host", host);
		properties.put("mail.smtp.port", port);
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.starttls.enable", "true");

		// creates a new session with an authenticator
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(userName, password);
			}
		};

		Session session = Session.getInstance(properties, auth);

		// creates a new e-mail message
		Message msg = new MimeMessage(session);

		msg.setFrom(new InternetAddress(userName));
		InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
		msg.setRecipients(Message.RecipientType.TO, toAddresses);
		msg.setSubject(subject);
		msg.setSentDate(new Date());
		// set plain text message
		msg.setText(message);

		// sends the e-mail
		Transport.send(msg);

	}

	/**
	 * Test the send e-mail method
	 *
	 */
	public static void main(String[] args) {
		// SMTP server information
		String host = "smtp.gmail.com";
		String port = "587";
		String mailFrom = "user_email";
		String password = "email_pass";

		// outgoing message information
		String mailTo = "recipient_email";
		String subject = "Hello my friend";
		String message = "Hi guy, Hope you are doing well. Duke.";

		PlainTextEmailSender mailer = new PlainTextEmailSender();

		try {
			mailer.sendPlainTextEmail(host, port, mailFrom, password, mailTo,
					subject, message);
			System.out.println("Email sent.");
		} catch (Exception ex) {
			System.out.println("Failed to sent email.");
			ex.printStackTrace();
		}
	}
}

The SMTP server used in the program above is Gmail. Change mailFrom and password corresponding to your e-mail account.

 

Other JavaMail Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (PlainTextEmailSender.java)PlainTextEmailSender.java[Java source code]2 kB

Add comment

   


Comments 

#20Sebastian leyton2021-04-12 02:04
Hola mundo que tal
ex
Quote
#19Hakim2020-11-10 03:38
If it doesn't work, make sure to disable your antivirus.
Quote
#18ashok2019-12-05 23:03
i tried exact code above
i face this execption
java.net.SocketException: Software caused connection abort: socket write error
Quote
#17G Bharath2019-09-05 01:56
Failed to sent email.
javax.mail.SendFailedException: Sending failed;nested exception is:
class javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. x5sm1264158pfi.165 - gsmtp
Quote
#16Karthi2018-12-31 03:46
When i am Run this Code ti shows
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
Quote