Sunday, August 9, 2009

How To send mail using JSP

To make sending mail program using only JSP, you need to first download mail.jar and activation.jar( download these from sun site) and place them under WEB0INF/lib folder of TOMCAT web server.
you can configure either your smtp sever or if you dont have your own smtp thn you can use others like google,yahoo,rediff etc.
here I am providing code for google smtp(smtp.gmail.com).

CODE :

<% @ page import="java.sql.*"
<% @ page import="java.lang.*"
<% @ page import="java.io.*"
<% @ page import="java.util.*"
<% @ page import="java.sql.Driver"
<% @ page import="javax.mail.*"
<% @ page import="javax.mail.Session"
<% @ page import="javax.mail.internet.*"
<% @ page import="javax.activation.*"
<% @ page import="javax.mail.internet.MimeMessage"

<%

try {
String smtpHost="smtp.gmail.com";
int smtpPort=587;
String from="yourmail@gmail.com";
String to= where you want to send mails;
String subject="Mail subject line";
String content=" Hi, this is mail content";
// Create a mail session
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", ""+smtpPort);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true"); //google needs thisauthorization

// Construct the message for recipient
Message msg = new MimeMessage(javax.mail.Session.getInstance(props, new javax.mail.Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication("yourmail@gmail.com","yourpassword");}}));

msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(content);

// Send the message
Transport.send(msg);

}

catch(MessagingException msge){

out.println("Mail sending error: "+msge.getMessage());}

catch(Exception e){out.println("exception:"+e.getMessage());

}


That's it.

If u have any problem u can post your comment here.
I'll be happy to help you :)

Total Pageviews