Sending Email using JavaMail API
Sending Email using JavaMail API
You can use one of the following techniques to get the SMTP server:There are various ways to send email using JavaMail API. For this purpose, you must have SMTP server that is responsible to send mails.
- 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 aproches to send email using javamail API. But we should learn the basic steps to send email from java application. |
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
The javax.mail.Session class provides two methods to get the object of session, Session.getDefaultInstance() method and Session.getInstance() method. You can use anyone method to get the session object. Examples of these methods are as follows:
Syntax of getDefaultInstance() method
There are two methods to get the session object by using the getDefaultInstance() method. It returns the default session.
Example of getDefaultInstance() method
Syntax of getInstance() method
There are two methods to get the session object by using the getInstance() method. It returns the new session.
- public static Session getInstance(Properties props)
- public static Session getInstance(Properties props,Authenticator auth)
- </pre></div>
- <h4 class="h4">Example of getDefaultInstance() method</h4>
- <div class="codeblock"><pre name="code" class="java" >
- Properties properties=new Properties();
- //fill all the informations 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: |
Now message object has been created but to store information in this object MimeMessage class provides many methods. Let's see methods provided by the MimeMessage class: |
Commonly used methods of MimeMessage class
1) public void setFrom(Address address): is used to set the from header field. |
2) public void addRecipients(Message.RecipientType type, String addresses): is used to add the given address to the recipient type. |
3) public void setSubject(String subject): is used to set the subject header field. |
4) public void setText(String textmessage) is used to set the text as the message content using text/plain MIME type. |
Example to compose the message:
3) Send the message
The javax.mail.Transport class provides method to send the message. |
Commonly used methods of Transport class
1) public static void send(Message message): is used send the message. |
2) public static void send(Message message, Address[] address): is used send the message to the given addresses. |
Example to send the message:
Simple example of sending email using JavaMail API
In this example, we are going to learn how to send email by SMTP server installed on the machine e.g. Postcast server, Apache James server, Cmail server etc. If you want to send email by using your SMTP server provided by the host provider, see the example after this one. |
For sending the email using JavaMail API, you need to load the two jar files:
|
- import java.util.*;
- import javax.mail.*;
- import javax.mail.internet.*;
- import javax.activation.*;
- public class SendEmail
- {
- public static void main(String [] args){
- String to = "pnkjtiwari446@gmail.com";//change accordingly
- String from = "pankaj0590@gmail.com";change accordingly
- String host = "localhost";//or IP address
- //Get the session object
- Properties properties = System.getProperties();
- properties.setProperty("mail.smtp.host", host);
- Session session = Session.getDefaultInstance(properties);
- //compose the message
- try{
- MimeMessage message = new MimeMessage(session);
- message.setFrom(new InternetAddress(from));
- message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
- message.setSubject("Ping");
- message.setText("Hello, this is example of sending email ");
- // Send message
- Transport.send(message);
- System.out.println("message sent successfully....");
- }catch (MessagingException mex) {mex.printStackTrace();}
- }
- }
In this example, we are going to learn how to send email by SMTP server installed on the machine e.g. Postcast server, Apache James server, Cmail server etc. If you want to send email by using your SMTP server provided by the host provider, see the example after this one.
To run this example, you need to load two jar files. There are 4 ways to load the jar file. One of the way is set classpath. Let's see how to run this example:
Load the jar file | c:\> set classpath=mail.jar;activation.jar;.; |
compile the source file | c:\> javac SendEmail.java |
run by | c:\> java SendEmail |
Example of sending email using JavaMail API through the SMTP server provided by the host provider
If you are using the SMTP server provided by the host provider e.g. mail.java.com , you need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password. |
If you are sending the email using JavaMail API, load the two jar files:
|
- import java.util.Properties;
- import javax.mail.*;
- import javax.mail.internet.*;
- public class SendMailBySite {
- public static void main(String[] args) {
- String host="mail.javatpoint.com";
- final String user="pankajl@java.com";//change accordingly
- final String password="xxxxx";//change accordingly
- String to="pankaj0590@gmail.com";//change accordingly
- //Get the session object
- Properties props = new Properties();
- props.put("mail.smtp.host",host);
- props.put("mail.smtp.auth", "true");
- Session session = Session.getDefaultInstance(props,
- new javax.mail.Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(user,password);
- }
- });
- //Compose the message
- try {
- MimeMessage message = new MimeMessage(session);
- message.setFrom(new InternetAddress(user));
- message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
- message.setSubject("java");
- message.setText("This is simple program of sending email using JavaMail API");
- //send the message
- Transport.send(message);
- System.out.println("message sent successfully...");
- } catch (MessagingException e) {e.printStackTrace();}
- }
- }
As you can see in the above example, userid and password need to be authenticated. As, this program illustrates, you can send email easily. Change the username and password accordingly. Let's see how to run it once again by simple technique:
Load the jar file | c:\> set classpath=mail.jar;activation.jar;.; |
compile the source file | c:\> javac SendMailBySite.java |
run by | c:\> java SendMailBySite |
JavaMail Architecture
Java Mail API Tutorial
The JavaMail API provides protocol-independent and plateform-independent framework for sending and receiving mails.The JavaMail is an API that is used to compose, write and read electronic messages (emails).
The javax.mail and javax.mail.activation packages contains the core classes of JavaMail API.
The JavaMail facility can be applied to many events. It can be used at the time of registering the user (sending notification such as thanks for your interest to my site), forgot password (sending password to the users email id), sending notifications for important updates etc. So there can be various usage of java mail api.
Protocols used in JavaMail API
There are some protocols that are used in JavaMail API.
|
SMTP
SMTP is an acronym for Simple Mail Transfer Protocol. It provides a mechanism to deliver the email. We can use Apache James server, Postcast server, cmail server etc. as an SMTP server. But if we purchase the host space, an SMTP server is bydefault provided by the host provider. For example, my smtp server is mail.javatpoint.com. If we use the SMTP server provided by the host provider, authentication is required for sending and receiving emails.
POP
POP is an acronym for Post Office Protocol, also known as POP3. It provides a mechanism to receive the email. It provides support for single mail box for each user. We can use Apache James server, cmail server etc. as an POP server. But if we purchase the host space, an POP server is bydefault provided by the host provider. For example, the pop server provided by the host prvider for my site is mail.javatpoint.com. This protocol is defined in RFC 1939.
IMAP
IMAP is an acronym for Internet Message Access Protocol. IMAP is an advanced protocol for receiving messages. It provides support for multiple mail box for each user ,in addition to, mailbox can be shared by multiple users. It is defined in RFC 2060.
MIME
Multiple Internet Mail Extension (MIME) tells the browser what is being sent e.g. attachment, format of the messages etc. It is not known as mail transfer protocol but it is used by your mail program. |
NNTP and Others
There are many protocols that are provided by third-party providers. Some of them are Network News Transfer Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc.
JavaMail Architecture
The java application uses JavaMail API to compose, send and receive emails. The JavaMail API uses SPI (Service Provider Interfaces) that provides the intermediatory services to the java application to deal with the different protocols. Let's understand it with the figure given below:
JavaMail API Core Classes
There are two packages that are used in Java Mail API: javax.mail and javax.mail.internet package. These packages contains many classes for Java Mail API. They are:
- javax.mail.Session class
- javax.mail.Message class
- javax.mail.internet.MimeMessage class
- javax.mail.Address class
- javax.mail.internet.InternetAddress class
- javax.mail.Authenticator class
- javax.mail.PasswordAuthentication class
- javax.mail.Transport class
- javax.mail.Store class
- javax.mail.Folder class etc.
We will know about these class one by one when it is getting used.
How to upload and download file from desire folder using struts2.0
Let see the Simple Example for upload and download file from desire folder
/****** Action Class for saving file from desire folder ***/
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import com.opensymphony.xwork2.ActionSupport;
public class WebAction extends ActionSupport {
private File myfile;
private String myfileFileName;
private String myfileContentType;
private String filePathToSaveInDB;
public String openHome() {
return "open";
}
public String uploadFileToMyFolder() {
try {
ServletContext servletContext = ServletActionContext.getServletContext();
String path = "MyFolder/";
//getting the path to where the images will be uploaded
String filePath = servletContext.getRealPath(path);
File uploadDir = new File(filePath);
//if the folder does not exits, creating it
if (uploadDir.exists() == false) {
uploadDir.mkdirs();
}
setFilePathToSaveInDB(path + "/" + myfileFileName);
FileUtils.copyFile(myfile, new File(uploadDir, myfileFileName));
} catch (Exception e) {
System.out.println("Exception : " + e);
addActionError(e.getMessage());
return "failure";
}
return "success";
}
// GETTER AND SETTER GOES HERE
Struts.xml file
<action name="uploadFileToMyFolder" method="uploadFileToMyFolder" class="com.debraj.WebAction">
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>
<param name="allowedTypes">
image/png,image/gif,image/jpeg,image/jpg
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">/pages/web/Success.jsp</result>
<result name="failure">/pages/web/failure.jsp</result>
</action>
Home.jsp for fire Action
<!DOCTYPE HTML>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title><s:text name="Struts2 File Upload" /></title>
</head>
<body>
<div>
<s:form id="uploadFileToMyFolder" name="uploadFileToMyFolder" action="uploadFileToMyFolder" enctype="multipart/form-data">
<s:text name="Upload Image : " />
<s:file name="myfile" id="myfile"/>
<s:submit name="submit"/>
</s:form>
</div>
</body>
</html>
Success.jsp
<!DOCTYPE HTML>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title><s:text name="Struts2 File Upload Success" /></title>
</head>
<body>
<div>
<s:actionmessage />
<s:property value="myfile"/><br />
<s:property value="myfileFileName"/><br />
<s:property value="myfileContentType"/><br />
<img src="<s:text name='%{filePathToSaveInDB}'/>"/><br />
</div>
</body>
</html>
fail.jsp
<!DOCTYPE HTML>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title><s:text name="Struts2 File Upload Failure" /></title>
</head>
<body>
<div>
<s:actionerror />
</div>
</body>
</html>
For Downloading File form desire Folder
package pankaj;
import java.sql.*;
import java.io.*;
import java.util.*;
public class Download {
static ArrayList arr=new ArrayList();
private static String assign_name,submit_date,attach1,reg_no;
public ArrayList getArr() {
return arr;
}
public void setArr(ArrayList arr) {
this.arr = arr;
}
public String getReg_no() {
return reg_no;
}
public void setReg_no(String reg_no) {
this.reg_no = reg_no;
}
public String getAssign_name() {
return assign_name;
}
public void setAssign_name(String assign_name) {
this.assign_name = assign_name;
}
public String getSubmit_date() {
return submit_date;
}
public void setSubmit_date(String submit_date) {
this.submit_date = submit_date;
}
public static String getAttach1() {
return attach1;
}
public static void setAttach1(String attach1) {
Download.attach1 = attach1;
}
public static ArrayList dd(String n)throws Exception
{
System.out.println("NAME"+n);
Class.forName("oracle.jdbc.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","oracle");
Statement st=con.createStatement();
//ResultSet rs=st.executeQuery("select assign.attach1,assign.assign_name,assign.submitdate from stureg inner join assign on assign.classname = stureg.classname and assign.sectionname=stureg.section where stureg.username='"+n+"'");
ResultSet rs1=st.executeQuery("SELECT * FROM STUREG WHERE USERNAME='"+n+"'");
String classname=null;
String section=null;
while(rs1.next())
{
classname=rs1.getString("CLASSNAME");
section=rs1.getString("SECTION");
}
ResultSet rs=st.executeQuery("SELECT * FROM ASSIGN WHERE CLASSNAME='"+classname+"' AND SECTIONNAME='"+section+"'");
while(rs.next())
{
arr.add(rs.getString("ASSIGN_NAME")+"@@"+rs.getString("SUBMITDATE")+"@@"+rs.getString("ATTACH1")+"@@"+rs.getString("SUBJECT"));
}
return arr;
}
}
download.jsp
<%@page import="java.sql.*"%>
<%@page import="pankaj.Download,java.util.*" %>
<%@taglib uri="/struts-tags" prefix="s" %>
<%
String n=(String)session.getAttribute("user");
out.println("NAme:"+n);
ArrayList arr;
arr=Download.dd(n);
/* arr=Download.dd(request.getParameter("ver"));
//out.println(request.getParameter("ver"));
Class.forName("oracle.jdbc.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","oracle");
Statement st=con.createStatement();
Download d=new Download();
ResultSet rs1=st.executeQuery("SELECT * FROM STUREG WHERE USERNAME='"+n+"'");
String classname=null;
String section=null;
while(rs1.next())
{
classname=rs1.getString("CLASSNAME");
section=rs1.getString("SECTION");
}
//String s=d.getReg_no();
//out.println("NAME:"+s);
ResultSet rs=st.executeQuery("select Attach1 from assign where SECTIONNAME='"+section+"' and CLASSNAME='"+classname+"'");
rs.next();*/
%>
<table class="normal-table m-bot-30" cellspacing='0'>
<thead>
<tr>
<th width="20%" class="first">Assignment Name</th>
<th width="23%">Submit Date</th>
<th width="20%">Subject</th>
<th colspan="2"></th>
</tr>
</thead>
<tbody>
<%
for(Object obj:arr)
{
String newlst1[]=obj.toString().split("@@");
%>
<tr>
<td><%=newlst1[0] %></td>
<td><%=newlst1[1] %></td>
<td><%=newlst1[3] %></td>
<td width="20%" ><a href="down.jsp?file=<%=newlst1[2] %>">Download</a></td>
<%}
arr.clear();
%>
</tbody>
</table>
</div>
Read file from desire folder
down.jsp
<%
String filename = request.getParameter("file");
out.println("File"+filename);
String filepath = "C:/Server/webapps/School/UploadFile/";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename"+filename);
java.io.FileInputStream fileInputStream=new java.io.FileInputStream(filepath+filename);
int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
%>
/****** Action Class for saving file from desire folder ***/
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import com.opensymphony.xwork2.ActionSupport;
public class WebAction extends ActionSupport {
private File myfile;
private String myfileFileName;
private String myfileContentType;
private String filePathToSaveInDB;
public String openHome() {
return "open";
}
public String uploadFileToMyFolder() {
try {
ServletContext servletContext = ServletActionContext.getServletContext();
String path = "MyFolder/";
//getting the path to where the images will be uploaded
String filePath = servletContext.getRealPath(path);
File uploadDir = new File(filePath);
//if the folder does not exits, creating it
if (uploadDir.exists() == false) {
uploadDir.mkdirs();
}
setFilePathToSaveInDB(path + "/" + myfileFileName);
FileUtils.copyFile(myfile, new File(uploadDir, myfileFileName));
} catch (Exception e) {
System.out.println("Exception : " + e);
addActionError(e.getMessage());
return "failure";
}
return "success";
}
// GETTER AND SETTER GOES HERE
Struts.xml file
<action name="uploadFileToMyFolder" method="uploadFileToMyFolder" class="com.debraj.WebAction">
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>
<param name="allowedTypes">
image/png,image/gif,image/jpeg,image/jpg
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">/pages/web/Success.jsp</result>
<result name="failure">/pages/web/failure.jsp</result>
</action>
Home.jsp for fire Action
<!DOCTYPE HTML>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title><s:text name="Struts2 File Upload" /></title>
</head>
<body>
<div>
<s:form id="uploadFileToMyFolder" name="uploadFileToMyFolder" action="uploadFileToMyFolder" enctype="multipart/form-data">
<s:text name="Upload Image : " />
<s:file name="myfile" id="myfile"/>
<s:submit name="submit"/>
</s:form>
</div>
</body>
</html>
Success.jsp
<!DOCTYPE HTML>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title><s:text name="Struts2 File Upload Success" /></title>
</head>
<body>
<div>
<s:actionmessage />
<s:property value="myfile"/><br />
<s:property value="myfileFileName"/><br />
<s:property value="myfileContentType"/><br />
<img src="<s:text name='%{filePathToSaveInDB}'/>"/><br />
</div>
</body>
</html>
fail.jsp
<!DOCTYPE HTML>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title><s:text name="Struts2 File Upload Failure" /></title>
</head>
<body>
<div>
<s:actionerror />
</div>
</body>
</html>
For Downloading File form desire Folder
package pankaj;
import java.sql.*;
import java.io.*;
import java.util.*;
public class Download {
static ArrayList arr=new ArrayList();
private static String assign_name,submit_date,attach1,reg_no;
public ArrayList getArr() {
return arr;
}
public void setArr(ArrayList arr) {
this.arr = arr;
}
public String getReg_no() {
return reg_no;
}
public void setReg_no(String reg_no) {
this.reg_no = reg_no;
}
public String getAssign_name() {
return assign_name;
}
public void setAssign_name(String assign_name) {
this.assign_name = assign_name;
}
public String getSubmit_date() {
return submit_date;
}
public void setSubmit_date(String submit_date) {
this.submit_date = submit_date;
}
public static String getAttach1() {
return attach1;
}
public static void setAttach1(String attach1) {
Download.attach1 = attach1;
}
public static ArrayList dd(String n)throws Exception
{
System.out.println("NAME"+n);
Class.forName("oracle.jdbc.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","oracle");
Statement st=con.createStatement();
//ResultSet rs=st.executeQuery("select assign.attach1,assign.assign_name,assign.submitdate from stureg inner join assign on assign.classname = stureg.classname and assign.sectionname=stureg.section where stureg.username='"+n+"'");
ResultSet rs1=st.executeQuery("SELECT * FROM STUREG WHERE USERNAME='"+n+"'");
String classname=null;
String section=null;
while(rs1.next())
{
classname=rs1.getString("CLASSNAME");
section=rs1.getString("SECTION");
}
ResultSet rs=st.executeQuery("SELECT * FROM ASSIGN WHERE CLASSNAME='"+classname+"' AND SECTIONNAME='"+section+"'");
while(rs.next())
{
arr.add(rs.getString("ASSIGN_NAME")+"@@"+rs.getString("SUBMITDATE")+"@@"+rs.getString("ATTACH1")+"@@"+rs.getString("SUBJECT"));
}
return arr;
}
}
download.jsp
<%@page import="java.sql.*"%>
<%@page import="pankaj.Download,java.util.*" %>
<%@taglib uri="/struts-tags" prefix="s" %>
<%
String n=(String)session.getAttribute("user");
out.println("NAme:"+n);
ArrayList arr;
arr=Download.dd(n);
/* arr=Download.dd(request.getParameter("ver"));
//out.println(request.getParameter("ver"));
Class.forName("oracle.jdbc.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","oracle");
Statement st=con.createStatement();
Download d=new Download();
ResultSet rs1=st.executeQuery("SELECT * FROM STUREG WHERE USERNAME='"+n+"'");
String classname=null;
String section=null;
while(rs1.next())
{
classname=rs1.getString("CLASSNAME");
section=rs1.getString("SECTION");
}
//String s=d.getReg_no();
//out.println("NAME:"+s);
ResultSet rs=st.executeQuery("select Attach1 from assign where SECTIONNAME='"+section+"' and CLASSNAME='"+classname+"'");
rs.next();*/
%>
<table class="normal-table m-bot-30" cellspacing='0'>
<thead>
<tr>
<th width="20%" class="first">Assignment Name</th>
<th width="23%">Submit Date</th>
<th width="20%">Subject</th>
<th colspan="2"></th>
</tr>
</thead>
<tbody>
<%
for(Object obj:arr)
{
String newlst1[]=obj.toString().split("@@");
%>
<tr>
<td><%=newlst1[0] %></td>
<td><%=newlst1[1] %></td>
<td><%=newlst1[3] %></td>
<td width="20%" ><a href="down.jsp?file=<%=newlst1[2] %>">Download</a></td>
<%}
arr.clear();
%>
</tbody>
</table>
</div>
Read file from desire folder
down.jsp
<%
String filename = request.getParameter("file");
out.println("File"+filename);
String filepath = "C:/Server/webapps/School/UploadFile/";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename"+filename);
java.io.FileInputStream fileInputStream=new java.io.FileInputStream(filepath+filename);
int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
%>