JavaMail API – Sending Email from JAVA, SMTP Server example

JavaMail API – Sending Email from JAVA via any SMTP Server example

There are various ways to send email using JavaMail API. For this purpose, you must have SMTP server that is responsible to send mails.

You can use one of the following techniques to get the SMTP server: SMTP servers provides host, port, user/password to send emails.

  • Install and use any SMTP server such as Postcast server, Apache James server, cmail server etc.
  • Use the SMTP server provided by the host provider e.g. my SMTP server is mail.gopaldas.org
  • Use the SMTP Server provided by other companies e.g. gmail etc.

Here, we are going to learn how to send email using javamail API. But we should learn the basic steps to send email from java application.

There are following three steps to send email using JavaMail. They are as follows:

  •     Get the session object that stores all the information of host like host name, username, password etc.
  •     compose the message
  •     send the message

There are two methods to get the session object by using the getDefaultInstance() method and getInstance().

public static Session getDefaultInstance(Properties props)
public static Session getDefaultInstance(Properties props,Authenticator auth)

public static Session getInstance(Properties props)
public static Session getInstance(Properties props,Authenticator auth)

Properties properties=new Properties();
//fill all the informations like host name etc.
Session session=Session.getInstance(properties,null);

create the message, you need to pass session object in MimeMessage class constructor.

For example:

MimeMessage message=new MimeMessage(session);

For sending the email using JavaMail API, you need to load the two jar files in your classpath –

  •     mail.jar
  •     activation.jar

Gopal Das
Follow me

Gopal Das

Founder at GopalDas.Org
He is a technology evangelist, Salesforce trainer, blogger, and working as a Salesforce Technical Lead. After working in Java based project implementation, he jumped to the Salesforce system on a whim and never looked back. He fell in love with Salesforce’s flexibility, scalability, and power. He expanded his knowledge of the platform and became a Certified App Builder, Administrator, Platform Developer I, SalesCloud Consultant while leading the Salesforce implementation and technology needs. He has worked in a wide variety of applications/services like desktop, web and mobile applications.
Gopal Das
Follow me

Leave a Reply

Your email address will not be published. Required fields are marked *