Monday, 23 December 2013

Java - Sending Email using JavaMail API

The Java Mail API provides support for sending and receiving electronic mail messages. The API provides a plug-in architecture where vendor’s implementation for their own proprietary protocols can be dynamically discovered and used at the run time. Sun provides a reference implementation and its supports the following protocols namely,

§  Internet Mail Access Protocol (IMAP)
§  Simple Mail Transfer Protocol (SMTP)
§  Post Office Protocol 3(POP 3)
In this tip, let us see how to send mail using the Java Mail API. Following is the complete code listing for sending a mail from a Java Application,

For this you have to download java-mail-1.4.4.jar


package com.mohan.javaexamples;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendGMail {

            public static void sendMail(String from, String to, String sub, String text)
                                    throws UnsupportedEncodingException, MessagingException {
//using TLS
                        Properties propsTLS = new Properties();
                        propsTLS.put("mail.transport.protocol", "smtp");
                        propsTLS.put("mail.smtp.host", "smtp.gmail.com");
                        propsTLS.put("mail.smtp.auth", "true");
                        propsTLS.put("mail.smtp.starttls.enable", "true");

                        Session session = Session.getDefaultInstance(propsTLS,
                                                new javax.mail.Authenticator() {
                                                            protected PasswordAuthentication getPasswordAuthentication() {
                                                                        return new PasswordAuthentication(
                                                                                                "gmailUsername@gmail.com", "gmailPassword");// Specify the Username and the PassWord
                                                            }
                                                });
                        session.setDebug(true);

                        Message message = new MimeMessage(session);
                        message.setFrom(new InternetAddress("gmailUsername@gmail.com",
                                                "Username"));
                        message.setRecipients(Message.RecipientType.TO,
                                                InternetAddress.parse("gmailReciverUsername@gmail.com"));
message.setSubject("Test mail program  using TLS techniques ....!"); //specify subject
                        message.setText("good job mohan ! keep it up .."); //specify text/body
                         message.setSentDate(new Date());

                        Transport transport = session.getTransport();
                        transport.connect("smtp.gmail.com", 587, "gmailUsername@gmail.com",
                                                "gmailPassword");
                        Transport.send(message, message.getAllRecipients());
                        transport.close();

                        System.out.println("------------------------------------------------------------------------");

//using SSL

                        Properties propSSL = new Properties();
                        propsTLS.put("mail.transport.protocol", "smtps");
                        propSSL.put("mail.smtps.host", "smtp.infostretch.com");
                        propSSL.put("mail.smtp.socketFactory.class",
                                                "javax.net.ssl.SSLSocketFactory");
       propSSL.put("mail.smtp.socketFactory.fallback", "false");
                        propSSL.put("mail.smtps.auth", "true");

                        Session session2 = Session.getDefaultInstance(propSSL,
                                                new javax.mail.Authenticator() {
                                                            protected PasswordAuthentication getPasswordAuthentication() {
                                                                        return new PasswordAuthentication(
                                                                                                "gmailUsername@gmail.com", "gmailPassword");// Specify the Username and the PassWord
                                                            }
                                                });
                        session2.setDebug(true);

                        Message message2 = new MimeMessage(session2);

                        message2.setFrom(new InternetAddress("gmailUsername@gmail.com",
                                                "Username"));
                        message2.setRecipients(Message.RecipientType.TO,
                                                InternetAddress.parse("gmailReciverUsername@gmail.com"));
                        message2.setSubject("Test mail program  using SSL!"); //specify subject
                        message2.setText("good job mohan ! keep it up .."); //specify text/body
                        message2.setSentDate(new Date());

                        Transport transportSSl = session2.getTransport();
                        transportSSl.connect("smtp.gmail.com", 465,"gmailUsername@gmail.com", "gmailPassword");
                        Transport.send(message2, message2.getAllRecipients());
                        transportSSl.close();
            }

            public static void main(String[] args) throws UnsupportedEncodingException,
                                    MessagingException {
                        System.out.println("sending mail .........!");
                        sendMail(null, null, null, null);
            }

}

Friday, 20 December 2013

File Upload and Download using Java to FTP

File Upload and Download is always a handy utility to know. There will be some need to upload a file to an FTP server, like if you generate a report or store some data in .xls file, then it needs to be uploaded to a FTP server for further use. Likewise we need to download some data (data stored in.xls files) for manipulation from the server in our projects. Here we have the code to do this for us. The File Upload/Download utility.


This file has the two methods one for upload a file to the FTP server and the other one for downloading the file from the FTP server. This program is written in very simple and easy strategy to upload or download the files using Java.

 It is using  BufferedOutputStream and BufferedInputStream IO classes. This program can be effectively reuse for your purpose in case if you want to upload or download the files from your website or your project work. If you like the program and feels it is very useful for you, please write comment and let us know if there is any improvement needed in the code.
If you have any doubts on the code and looking for the help on this code, please post your queries in the comments section.



package com.mohan.javaexamples;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

public class FIleLoadFtp {

      public FIleLoadFtp() {

      }

      public void upload() throws IOException {

            String ftpServer = "ftpservername";
            String userName = "username";
            String password = "password";
            File source = new File(
                        "location of file with Filename(which file, you want upload to ftp)");
            String fileName = source.getName();

            if (ftpServer != null && fileName != null && source != null) {
                  StringBuffer buffer = new StringBuffer("ftp://");
                  if (userName != null && password != null) {
                        buffer.append(userName);
                        buffer.append(':');
                        buffer.append(password);
                        buffer.append('@');
                  }
                  buffer.append(ftpServer);
                  buffer.append("//");
                  buffer.append(fileName);
                  buffer.append(";type=i");
                  BufferedInputStream bis = null;
                  BufferedOutputStream bos = null;

                  try {
                        URL url = new URL(buffer.toString());
                        System.out.println("Url : " + url);
                        URLConnection urlCon = url.openConnection();
                        System.out.println("UrlCon  : " + urlCon);
                        bos = new BufferedOutputStream(urlCon.getOutputStream());
                      bis = new BufferedInputStream(new FileInputStream(source));
                        int i;
                        while (((i = bis.read()) != -1)) {
                              bos.write(i);
                        }
                  } finally {
                        if (bis != null) {
                              try {
                                    bis.close();
                              } catch (IOException e) {
                                    e.getMessage();
                                    e.printStackTrace();
                              }
                        }
                        if (bos != null) {
                              try {
                                    bos.close();
                              } catch (IOException ioe) {
                                    ioe.getMessage();
                                    ioe.printStackTrace();
                              }
                        }
                  }
            } else {
                  System.out.println("Input is not available");
            }
      }

      public void download(String ftpServer, String userName, String password,
                  File destination, String fileName) throws IOException {
            if (ftpServer != null && fileName != null && destination != null) {
                  StringBuffer buffer = new StringBuffer("ftp://");
                  if (userName != null && password != null) {
                        buffer.append(userName);
                        buffer.append(':');
                        buffer.append(password);
                        buffer.append('@');
                  }
                  buffer.append(ftpServer);
                  buffer.append("//");
                  buffer.append(fileName);
                  buffer.append(";type=i");
                  BufferedInputStream bis = null;
                  BufferedOutputStream bos = null;

                  try {
                        URL url = new URL(buffer.toString());
                        System.out.println("url is ; " + url);
                        URLConnection urlCon = url.openConnection();
                        bis = new BufferedInputStream(urlCon.getInputStream());
    bos = new BufferedOutputStream(new FileOutputStream(destination.getName()));
                        int i;
                        while (((i = bis.read()) != -1)) {
                              bos.write(i);
                        }
                  } finally {
                        if (bos != null) {
                              try {
                                    bos.close();
                              } catch (IOException e) {
                                    e.printStackTrace();
                              }
                        }
                        if (bis != null) {
                              try {
                                    bis.close();
                              } catch (IOException ie) {
                 System.out.println("message : " + ie.getMessage());
                                    ie.printStackTrace();

                              }
                        }
                  }
            }
      }

      

}



Getting started with Elasticsearch and Node.js

  In this article we're going to look at using Node to connect to an Elasticsearch deployment, index some documents and perform a simple...