Using SendGrid with Codenvy

Create SendGrid Sample App using Codenvy Factory:



SendGrid is a cloud based Email infrastructure .Which relieves the complexity of maintaining the Email servers. It provides reliable delivery and scalability.
The Main Usage of the SendGrid is for sending Bulk emails which is like marketing emails. SendGrid provides different packages for sending emails for Bulk usage. Basic package is limited only for 200 Emails. SendGrid provides an API to integrate into different platform Applications to use their SMTP Severs for sending Emails.
The API is available for the different languages:

  • C#
  • Java
  • JavaScript
  • Perl
  • PHP
  • Python
  • Ruby
  • PHP using cURL

For Sending an Email from Java Application or from any other application First we need to register at sendgrid.com and make use of the login details for authentication into the SMTP Servers.
Configuration Details needs for SendGrid Email Client Application.
SMTP server: smtp.sendgrid.net
Username:
Password:

Create pom.xml File

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.codenvy</groupId>
  <artifactId>SendGrid-web</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>java-web-sample</name>

  <dependencies>
    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4.7</version>
    </dependency></dependencies>

  <build>
    <finalName>java-web-sample</finalName>
  </build>
</project>

Create Java Class

Here is the java Email Client Application Which Used for Sending Email.

package com.codenvy;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SimpleMail {

	private static final String SMTP_HOST_NAME = "smtp.sendgrid.net";
	private static final String SMTP_AUTH_USER = "anil14349";
	private static final String SMTP_AUTH_PWD = "linaku9*";

	public void sendMail(String from,String to,String sub,String msg) throws Exception {
		Properties props = new Properties();
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.smtp.host", SMTP_HOST_NAME);
		props.put("mail.smtp.port", 587);
		props.put("mail.smtp.auth", "true");

		Authenticator auth = new SMTPAuthenticator();
		Session mailSession = Session.getDefaultInstance(props, auth);
		// uncomment for debugging infos to stdout
		mailSession.setDebug(true);

			Transport transport = mailSession.getTransport();
			MimeMessage message = new MimeMessage(mailSession);
			Multipart multipart = new MimeMultipart();

			message.setContent(multipart);
			message.setFrom(new InternetAddress(from));
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					to));
			message.setSubject(sub);
			BodyPart part1 = new MimeBodyPart();
			part1.setText( msg );
			multipart.addBodyPart(part1);

			/*
			 * BodyPart part2 = new MimeBodyPart();part2.setContent(
			 * "<b>This is multipart mail and u read part2......</b>",
			 * "text/html"); multipart.addBodyPart(part2);
			 */

			transport.connect();
			transport.sendMessage(message, message
					.getRecipients(Message.RecipientType.TO));
			transport.close();
			}

	private class SMTPAuthenticator extends javax.mail.Authenticator {
		public PasswordAuthentication getPasswordAuthentication() {
			String username = SMTP_AUTH_USER;
			String password = SMTP_AUTH_PWD;
			return new PasswordAuthentication(username, password);
		}
	}
}

Create index.jsp File

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type"
      content="text/html; charset=ISO-8859-1">
    <script type="text/javascript">
function altRows(id) {
  if (document.getElementsByTagName) {

    var table = document.getElementById(id);
    var rows = table.getElementsByTagName("tr");

    for (i = 0; i < rows.length; i++) {
      if (i % 2 == 0) {
        rows[i].className = "evenrowcolor";
      } else {
        rows[i].className = "oddrowcolor";
      }
    }
  }
}
window.onload = function() {
  altRows('alternatecolor');
}

function validateForm() {
  var x = document.forms["sendGrid"]["from"].value;
  var atpos = x.indexOf("@");
  var dotpos = x.lastIndexOf(".");
  if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
    alert("From Address is Not a valid e-mail address");
    return false;
  }

  x = document.forms["sendGrid"]["to"].value;
     atpos = x.indexOf("@");
   dotpos = x.lastIndexOf(".");
  if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
    alert("To Address is Not a valid e-mail address");
    return false;
  }

 x = document.forms["sendGrid"]["subject"].value;
  if (x == null || x == "") {
    alert("Subject must be filled out");
    return false;
  }

 x = document.forms["sendGrid"]["msg"].value;
  if (x == null || x == "") {
    alert("Message must be filled out");
    return false;
  }
}

</script>

    <!-- CSS goes in the document HEAD or added to your external stylesheet -->
    <style type="text/css">
table.altrowstable {
  font-family: verdana, arial, sans-serif;
  font-size: 11px;
  color: #333333;
  border-width: 1px;
  border-color: #a9c6c9;
  border-collapse: collapse;
}

table.altrowstable th {
  border-width: 1px;
  padding: 8px;
  border-style: solid;
  border-color: #a9c6c9;
}

table.altrowstable td {
  border-width: 1px;
  padding: 8px;
  border-style: solid;
  border-color: #a9c6c9;
}

.oddrowcolor {
  background-color: #d4e3e5;
}

.evenrowcolor {
  background-color: #c3dde0;
}
</style>

    <title>Send Grid Tutorial</title>
  </head>
  <body>
    <form name="sendGrid" action="sendmail.jsp" method="get"
      onsubmit="return validateForm();">

      <center>
        <br />
        <table class="altrowstable" id="alternatecolor">
          <tr>
            <th colspan="2">
              SendGrid Tutorial
            </th>

          </tr>
          <tr>
            <td>
              From
            </td>
            <td>
              <input type="text" name="from" size="65"  />
          </tr>
          <tr>
            <td>
              To
            </td>
            <td>
              <input type="text" name="to" size="65" />
            </td>
          </tr>
          <tr>
            <td>
              Subject
            </td>
            <td>
              <input type="text" name="subject" size="65" />
            </td>
          </tr>
          <tr>
            <td>
              Message
            </td>
            <td>
              <textarea rows="4" cols="50" name="msg"></textarea>
            </td>
          </tr>
          <tr>
            <td align="center" colspan="2">
              <input type="submit" value="Send Mail" />
            </td>
          </tr>
        </table>

      </center>
    </form>
  </body>
</html>

Create sendmail.jsp

In index.jsp we’ll capture the input Fields (From email Address, To email Address,Subject and Message) data and sends it to sendmail.jsp.

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@page import="com.codenvy.SimpleMail"%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme() + "://"
      + request.getServerName() + ":" + request.getServerPort()
      + path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'sendmail.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
  <link rel="stylesheet" type="text/css" href="styles.css">
  -->

  </head>

  <body>
  <form action="index.jsp">
    <%
      boolean sent = true;
      try {
        SimpleMail sm = new SimpleMail();

        sm.sendMail(request.getParameter("from"), request
            .getParameter("to"), request.getParameter("subject"),
            request.getParameter("msg"));
      } catch (Exception e) {
        sent = false;
      }
    %>
    <%
      if (sent) {
    %>Mail Sent Successfully to
    <%=request.getParameter("to")%><br/>
    <%
      } else {
    %><b>It seems there is an Exception While sending mail.Please try
      Again</b><br/>
    <%
      }
    %>

  <input type="submit" value="back to Prev Page"/>

    <br/>
    </form>
  </body>
</html>