Oct 22, 2014

JSP - Sending Email using Gmail

It's very simple to send email from jsp program. but to do this you must set the class path to mail.jar file. Following code will help you to send email from gmail account to any email address. If you want to send email from another account change the host and port.


<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 
<%@page import="java.util.Properties "%>
<%@page import="javax.mail.Message "%>
<%@page import="javax.mail.MessagingException "%>
<%@page import="javax.mail.Session "%>
<%@page import="javax.mail.Transport" %>
<%@page import="javax.mail.Message.RecipientType" %>
<%@page import="javax.mail.internet.AddressException" %>
<%@page import="javax.mail.internet.InternetAddress" %>
<%@page import="javax.mail.internet.MimeMessage" %>
<%@page import="javax.mail.PasswordAuthentication" %>

<%

   String msgToEmail = "Nifal.Nizar@hotmail.com";
   String msgSubject = "Easy Code Stuff";
   String msgBody = "This Is An Example To Send A Simple Email From JSP Program.";
   final String msgFromEmail = "Nifal.Nizar@gmail.com";
   final String msgFromPass = "AsiyaMariyam2014";

   Properties props = new Properties();

   try {
      props.put("mail.smtp.host", "smtp.gmail.com");
      props.put("mail.smtp.auth", "true");
      props.setProperty( "mail.smtp.port", "587");
      props.put("mail.smtp.starttls.enable", "true");

      Session sess = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(msgFromEmail, msgFromPass);
         }
      });

      MimeMessage message = new MimeMessage(sess);
      message.setFrom(new InternetAddress(msgFromEmail)); 
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(msgToEmail));
      message.setSubject(msgSubject);
      message.setText(msgBody);
      Transport.send(message);
      out.println("Email sent successfully..!!");
   } 
   catch (Exception e) {
      out.println(e);
   }
%>


Enjoy The Code...

No comments:

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...