How to send mail using Java Mail API?

SHARE & COMMENT :

The Java Mail API provides support for sending and receiving electronic mail messages. The API provides a plug-in architecture where vendor’s implementation for their own proprietary protocols can be dynamically discovered and used at the run time. Sun provides a reference implementation and its supports the following protocols namely,

also read:

  • Internet Mail Access Protocol (IMAP)
  • Simple Mail Transfer Protocol (SMTP)
  • Post Office Protocol 3(POP 3)

In this tip, let us see how to send mail using the Java Mail API. Following is the complete code listing for sending a mail from a Java Application,

SendMail.java

package tips.mails;

import java.util.Properties;

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

public class SendMail {

	private String from;
	private String to;
	private String subject;
	private String text;

	public SendMail(String from, String to, String subject, String text){
		this.from = from;
		this.to = to;
		this.subject = subject;
		this.text = text;
	}

	public void send(){

		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "465");

		Session mailSession = Session.getDefaultInstance(props);
		Message simpleMessage = new MimeMessage(mailSession);

		InternetAddress fromAddress = null;
		InternetAddress toAddress = null;
		try {
			fromAddress = new InternetAddress(from);
			toAddress = new InternetAddress(to);
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			simpleMessage.setFrom(fromAddress);
			simpleMessage.setRecipient(RecipientType.TO, toAddress);
			simpleMessage.setSubject(subject);
			simpleMessage.setText(text);

			Transport.send(simpleMessage);
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

The above program accepts the sender, receiver, subject and the data in its constructor. After giving this information, the mail can be sent by calling the SendMail.send() method. Let us have a deeper look into the implementation of this method.

The first thing is that a Mail Session has to be established with some properties for sending or receiving a mail. The mandatory property is the server name. In the above code, we have given the SMTP Mail server of Google. Then, it is optional to provide the port information, and it is needed if it is different from the default port of 25. Then we construct a Message object for the Mail session by populating the information like sender, receiver, subject and text. Then the message is sent by calling the Transport.send() method.

Let us test the above code by writing a simple test class which is given below,

SendMailTest.java

package tips.mails;

public class SendMailTest {

	public static void main(String[] args) {

		String from = "abc@gmail.com";
		String to = "xyz@gmail.com";
		String subject = "Test";
		String message = "A test message";

		SendMail sendMail = new SendMail(from, to, subject, message);
		sendMail.send();
	}
}

also read:

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. how a mail will be sent without any credentials. i mean there is no need of entering the gmail password?

    • suthukrish says:

      It is only the example program to send the mail. We need not have the server to setup for sending the mails. Is it your doubts?

    • suthukrish says:

      HI Sai,

      There is no need for the password, basically it is for only sending the mail. Why do you need gmail password, you are not going to login to your gmail. The receiver will receive as from address as your gmail address. But, it is not sent from the GMail server (Using your gmail account).

      Is it clear now?

      Thanks,
      Krishna

  2. it cannot work with yahoo or rediffmail .com username pls help me

  3. rupali says:

    when i tried it i got run time exception
    Exception in thread main java.lang.classformaterror : absent code attribute in methos is that is not native or abstract in class file javax/mail/internet/AddressException
    at
    java.lang.classloader.defineclass1<native method>

    need help

  4. it doesn’t work 4 me do i need setup 4 server ? help me plz

  5. This doesnt work man.

  6. well \n this \n is \n difficult \n to \n implement.

  7. i found it and i did a tuto to send mail with java

  8. Rashmi says:

    When I run this program I am getting Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream…help me plz

  9. any one got the mail to inbox?? i am not getting mail …how to get the mail please tell me

  10. Hello

  11. Hello

  12. Himanshu Saraswat says:

    but I do not see any authentication taking place in the code. This code will surely throw error

  13. where am i placing the password still it cant word here is the code

    import java.util.Properties;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    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;

    /**
    *
    * @author Admin
    */
    public class SendMailSSL {
    public static void main(String[] args) throws MessagingException
    {
    String to = “nahashonwambui@gmail.com”;//Reciver Address.
    Properties props = new Properties();
    props.put(“mail.smtp.host”, “smtp.gmail.com”);
    props.put(“mail.smtp.port”, “587″);
    props.put(“mail.smtp.auth”, “true”);
    props.put(“mail.smtp.starttls.enable”, “true”);
    Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator()
    {
    protected PasswordAuthentication getPasswordAuthentication(String from)
    {
    return new PasswordAuthentication(from,”0000000000000000″);
    }
    });
    Message message = new MimeMessage(mailSession);
    try {
    message.setFrom(new InternetAddress(“nahashonwaeru@gmail.com”));//Sender Id.
    } catch (AddressException ex) {
    Logger.getLogger(SendMailSSL.class.getName()).log(Level.SEVERE, null, ex);
    }
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(“Hello!”);
    message.setText(“Testing from Java Application…….”);

    // send message.
    Transport.send(message);
    System.out.println(“message sent successfully”);
    }
    }

  14. i am getting an exception while running this code Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/mail/util/SharedByteArrayInputStream

    at mail.email.send(email.java:40)

    at mail.SendMailText.main(SendMailText.java:15)

  15. Aman Raikwar says:

    Hi!

    this code is not working. can u pls help me out from this….

  16. Aman Raikwar says:

    Hi!

    this code is not working. can u pls help me out from this….

  17. Aman Raikwar says:

    Hi!

    this code is not working. can u pls help me out from this….

  18. Aman Raikwar says:

    Hi!

    this code is not working. can u pls help me out from this….

  19. Aman Raikwar says:

    Hi!

    this code is not working. can u pls help me out from this….

  20. Thanks for the post !! Really helpful.. Even this website http://www.compiletimeerror.com/2013/03/java-mail-api-send-email-from-java-code.html also address something similar.. Have a look.. May help..

  21. Thanks for the post !! Really helpful.. Even this website http://www.compiletimeerror.com/2013/03/java-mail-api-send-email-from-java-code.html also address something similar.. Have a look.. May help..

  22. tell me hw to create installation setup of java software …..

    satishkendre@gmail.com

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better