Sending
Email in Java
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:
- Install and use any SMTP server such as Postcast
server, Apache James server, cmail server etc. (or)
- Use the SMTP server provided by the host provider e.g.
my SMTP server is mail.javatpoint.com (or)
- Use the SMTP Server provided by other companies e.g.
gmail etc.
Here, we are going to learn above three
approaches to send email using javamail API. But we should learn the basic
steps to send email from java application.
|
Fig: Sending Email In Java |
Steps to send email using
JavaMail API
There are following three steps to send email
using JavaMail. They are as follows:
1. Get the session
object that stores all the information of host
like host name, username, password etc.
2. compose the message
3. send the message
1) Get
the session object
The javax.mail.Session class provides
two methods to get the object of session, Session.getDefaultInstance() method
and Session.getInstance() method. You can use any method to get the session
object.
Example
of getInstance() method
Properties properties=new Properties();
//fill all the information like host name etc.
Session session=Session.getInstance(properties,null);
2)
Compose the message
|
The
javax.mail.Message class provides methods to compose the message.
But
it is an abstract class so its subclass javax.mail.internet.
MimeMessage
class is mostly used.
|
To
create the message, you need to pass session object in MimeMessage
class constructor.
For Example:
|
|
MimeMessage message=new MimeMessage(session);
3)
Send the message
The javax.mail.Transport class provides
method to send the message.
|
|
|
Example to send the message:
Simple example of sending email in Java
To send email by SMTP
server installed on the machine e.g. Postcast
server, Apache James
server, Cmail server etc.
For sending the email
using JavaMail API, you need to load the two jar files:
|
|
|
No comments:
Post a Comment