Menus

Jun 7, 2016

Program to send email in JSP.


(Sharing is the most valuable work of this universe.
So don't forget to share. 
Help the world, help yourself.)

mail.jsp

<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%
final String username = "senderEmailAddress";
final String password = "senderPassword";
String result = null;
try {
Properties props = System.getProperties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "25");
props.put("mail.debug", "true");
props.put("mail.smtp.socketFactory.port", "25");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session emailSession = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password);
}
});
emailSession.setDebug(true);
Message message = new MimeMessage(emailSession);
message.setFrom(new InternetAddress(
username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("receiverEmailAddress"));
message.setSubject("Test mail from Java");
message.setText("Hello. this is a test");
Transport transport = emailSession.getTransport("smtps");
transport.connect("smtp.gmail.com", username, password);
transport.sendMessage(message, message.getAllRecipients());
result = "Successfully sent email";
} catch (MessagingException e) {
result = "Unable to send email"+e;
}
%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<p align="center">
<%
out.println("Result: " + result + "\n");
%>
</p>
</body>

</html>

No comments:

Post a Comment

Contact Form

Name

Email *

Message *