Wednesday, November 28, 2012

Shell script: format numbers


Shell script to format date in yyyy.mm.dd format
#!/bin/bash

year=2012

for (( c=1; c<=12; c++ ))
do
   month=$(printf "%02d" $c)

  for (( d=1; d<=15; d++ ))
  do
     day=$(printf "%02d" $d)
     echo $year.$month.$day
  done
done

Java : Send Email


Following is the code to send email using java. Download mail.jar and activation.jar to run the program.
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailProcessor {
 
 private String mailHost;
 private String from;
 private String to;
 private String subject;
 private String text;
 
  public static void main(String[] args)
 {
  EmailProcessor emp = new EmailProcessor("mailhost", "from@test.com", "to1@test.com,to2@test.com", "Subject", "Email Text");
  emp.send();
 }
 
 public EmailProcessor(String mailhost, String from, String to, String subject, String text){
  this.from = from;
  this.to = to;
  this.subject = subject;
  this.text = text;
  this.mailHost = mailhost;
 }
 
 public void send(){
 
  Properties props = new Properties();
  
  props.put("mail.smtp.host", mailHost);
 
  Session mailSession = Session.getDefaultInstance(props);
  Message simpleMessage = new MimeMessage(mailSession);
 
  InternetAddress fromAddress = null;
  InternetAddress[] toAddress = null;
  try {
   fromAddress = new InternetAddress(from);
   
   String[] toEmails = to.split(",");
            toAddress = new InternetAddress[toEmails.length];
            for (int i = 0; i < toEmails.length; i++)
            {
             toAddress[i] = new InternetAddress(toEmails[i].trim());
            }
  } catch (AddressException e) {
   Utility.logError(e.getMessage());
   e.printStackTrace();
  }
 
  try {
   simpleMessage.setFrom(fromAddress);
            simpleMessage.setRecipients(RecipientType.TO, toAddress);
   simpleMessage.setSubject(subject);
   simpleMessage.setText(text);
 
   Transport.send(simpleMessage);
  } catch (MessagingException e) {
   Utility.logError(e.getMessage());
   e.printStackTrace();
  }
 }
}