Friday, 24 March 2017

Send mail in JSP/Java using SMTP gmail

Sending mail in web applications are very useful tool. In this blog I will discus how to send e-mail using gmail SMTP.

Pre-requisite of mail sending programme:-

I presume that you have good knowledge of running a web application on Java server like Apache Tomcat or Glassfish etc.

You require following API to implement sending mail in Java-

  1. mail.jar- this file can be downloaded from here.
  2. activation.jar- this file can be downloaded from here.
  3. Or mail api from here.

So, download these and add it to your project. How to add external Jar file to a project see here.

Create a form to send mail:-

mail.html
<form name="emailForm" action="sendmail.jsp" method="post">
<table>
<tr><td><b><font color="red">To:
</td>
<td><b><b><input type="text" name="mail" placeholder="Enter sender mail-id"/><br/>
</td>
</tr>
<tr>
<td>
<b><font color="red">Subject:
</td>
<td>
<input type="text" name="sub" placeholder="Enter Subject Line"><br/>
</td>
</tr>
<tr>
<td>
<b><font color="red">Message Text:
</td>
<td>
<textarea rows="12" cols="80" name="mess"></textarea><br/>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Send" name="btn1">
</td>
<td>
<input type="reset" value="Reset">
</td>
</tr>
</table>
</form>

Java Code to send mail:-

sendmail.jsp

Import these packages in your send mail Java Code

<%@ page import="java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*" %>
<%@ page import="javax.activation.*" %>

if (request.getParameter("btn1") != null)
{
//Creating a result for getting status that messsage is delivered or not!
String result;

// Get recipient's email-ID, message & subject-line from mail.html page
final String to = request.getParameter("mail");
final String subject = request.getParameter("sub");
final String messg = request.getParameter("mess");
// Sender's email ID and password needs to be mentioned
final String from = "sender-mail@gmail.com";
final String pass = "sendermailpassword";
// Defining the gmail host
String host = "smtp.gmail.com";
// Creating Properties object
Properties props = new Properties();
// Defining properties
props.put("mail.smtp.ssl.enable","true");
props.put("mail.smtp.host", host);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.user", from);
props.put("mail.password", pass);
props.put("mail.port", "587"); // there are some other ports also available like 465 you can also use.
// Authorized the Session object.
Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, pass);
}
});
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(mailSession);

// Set From: header field of the header.
message.setFrom(new InternetAddress(from));

// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

// Set Subject: header field
message.setSubject(subject);

// Now set the actual message
message.setText(messg);

// Send message
Transport.send(message);
result = "Your mail sent successfully....";
out.println(result);
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: unable to send mail....";
out.println(mex);
out.println(result);}
}


If everything goes fine then you will be able to successfully send mail.

1. Apart from above you may also require to set your gmail account to allow less secure app to use your account. You may check it from here.


2. Some common mistakes can be find from here.

3. Some other help that may help you.

4 comments:

  1. Sir I am getting exception on running this code,
    com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1;nested exception is:java.net.ConnectException: Connection refused: connect Error: unable to send mail....

    ReplyDelete
    Replies
    1. Are you using proxy server to connect the internet? If yes the use direct connection e.g. your phone internet.

      Delete
    2. Using port 465 instead of 587 is working fine.

      Delete

Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...