Mail Send With Attachments

Sample Program To Send Mail from Java

/**
*
*/
package com.webaging.utils;

import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
* @author Ashwin
*
*/
public class MailSender {

/**
* @param from
* @param to
* @param subject
* @param message
* @throws Exception
*/
public static void sendMail(String host, String fromAddress,
List toAddresses, String subject, String messageContent,
String[] attachments) throws Exception {
// Create empty properties
try {
Properties props = System.getProperties();
props.put("mail.pop3.host", host);
Session session = Session.getInstance(props, null);

MimeMessage message = new MimeMessage(session);
InternetAddress from = new InternetAddress(fromAddress);
message.setFrom(from);
message.setSubject(subject);

for (Iterator it = toAddresses.iterator(); it.hasNext();) {
message.addRecipient(Message.RecipientType.TO,
new InternetAddress((String) it.next()));
}

Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(messageContent + "

", "text/html");
multipart.addBodyPart(messageBodyPart);

// add any file attachments to the message
addAtachments(attachments, multipart);

message.setContent(multipart);
// Now Send the message
Transport.send(message);

} catch (Exception e) {
throw e;
}

}

/**
* @param attachments
* @param multipart
* @throws MessagingException
* @throws AddressException
*/
protected static void addAtachments(String[] attachments,
Multipart multipart) throws MessagingException, AddressException {
for (int i = 0; i <= attachments.length - 1; i++) {
String filename = attachments[i];
MimeBodyPart attachmentBodyPart = new MimeBodyPart();

// use a JAF FileDataSource as it does MIME type detection
DataSource source = new FileDataSource(filename);
attachmentBodyPart.setDataHandler(new DataHandler(source));

// assume that the filename you want to send is the same as the
// actual file name - could alter this to remove the file path
attachmentBodyPart.setFileName(filename);

// add the attachment
multipart.addBodyPart(attachmentBodyPart);
}
}

}

Advertisements

Read Mail Java

Sample Program to Read Mail

package com.ashwin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.event.FolderListener;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailReaderUtility {

public static void main(String[] args) {
Authenticator auth = null;
Folder folder = null;
Store store = null;
String comment = "";
String subject = "";
String from = "";

try {

auth = new SMTPAuthenticator(args[0],args[1]);

// Create empty properties
Properties props = System.getProperties();
props.put("mail.pop3.host", args[2]);
// get session
Session session = Session.getDefaultInstance(props, auth);
// Get the store
store = session.getStore("pop3");
store.connect();
// Get folder
FolderListener arg0;
// store.addFolderListener();

// store.addFolderListener();
folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
// Get directory\\
Message message[] = folder.getMessages();
for (int i = 0, n = message.length; i < n; i++) {
Map dataStore = new HashMap();
Address[] addresses = message[i].getFrom();
InternetAddress address = (InternetAddress) addresses[0];
from = address.getAddress();
subject = message[i].getSubject();
dataStore.put("from", from);
dataStore.put("subject", subject);

if (((MimeMessage) message[i]).getContent() instanceof String) {
// content is texText
// System.out.println(((MimeMessage)
// message[i]).getContent());
comment = ((MimeMessage) message[i]).getContent()
.toString();
dataStore.put("comment", comment);
} else if (((MimeMessage) message[i]).getContent() instanceof Multipart
|| ((MimeMessage) message[i]).getContent() instanceof Part) {
Multipart multiPartcnt = (Multipart) ((MimeMessage) message[i])
.getContent();

Object content = message[i].getContent();
if (content instanceof Multipart) {
handleMultipart((Multipart) content, dataStore);
} else {
handlePart(message[i], dataStore);
}

comment = multiPartcnt.getBodyPart(0).getContent()
.toString();
// recursively iterate over container's contents to
// retrieve
// attachments
} else if (((MimeMessage) message[i]).getContent() instanceof Message) {
// message content could be a message itself
}

System.out.println("From: "+dataStore.get("from"));
System.out.println("Subject: "+dataStore.get("subject"));
String testComment = (String)dataStore.get("comment");
if(testComment.length() < 15){
System.out.println("Data: "+testComment.substring(0, testComment.length()));
}else{
System.out.println("Data: "+testComment.substring(0, 14));
}
System.out.println("------------------------------------");
}
}catch(Exception e){
e.printStackTrace();
}

}

public static void handleMultipart(Multipart multipart,
Map dataStore) throws MessagingException,
IOException {
for (int i = 0, n = multipart.getCount(); i < n; i++) {
handlePart(multipart.getBodyPart(i), dataStore);
}
}

public static void handlePart(Part part, Map dataStore)
throws MessagingException, IOException {
String disposition = part.getDisposition();
String contentType = part.getContentType();
// System.out.println("In Handle Part : " + contentType);
if (disposition == null) { // When just body
// System.out.println("Null: " + contentType);
// Check if plain
if ((contentType.length() >= 10)
&& (contentType.toLowerCase().substring(0, 10)
.equals("text/plain"))) {
// part.writeTo(System.out);
dataStore.put("comment", part.getContent().toString());
} else { // Don't think this will happen
// System.out.println("Other body: " + contentType);
dataStore.put("comment", part.getContent().toString());
}
} else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
// System.out.println("Attachment: " + part.getFileName() + " : "+
// contentType);
List fileNames = (List) dataStore.get("attachment");
if (fileNames == null) {
fileNames = new ArrayList();
}
fileNames.add(part.getFileName());
dataStore.put("attachment", fileNames);
//saveFile(part.getFileName(), part.getInputStream());
} else if (disposition.equalsIgnoreCase(Part.INLINE)) {
// System.out.println("Inline: " + part.getFileName() + " : " +
// contentType);
//saveFile(part.getFileName(), part.getInputStream());
} else { // Should never happen
// System.out.println("Other: " + disposition);
}
}
}

SMTP Authenticator


/**
*
*/
package com.ashwin;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
* @author ashwin
*
*/
public class SMTPAuthenticator extends Authenticator
{
String masteruser = null;
String masterpswd = null;

SMTPAuthenticator(String user, String password)
{
masteruser = user;
masterpswd = password;
}
public PasswordAuthentication getPasswordAuthentication()
{

return new PasswordAuthentication(masteruser, masterpswd);
}
}

Signature Capture In Java

Want to create paint like application where we can capture signature in java. Here is sample code to do it


/**
 * 
 */
package com.ashwin;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;

/**
 * @author Ashwin
 * 
 */
public class SignatureCapture extends JApplet {

	public BufferedImage image = null;
	private JPanel canvas = new JPanel();
	private JPanel colorPanel = new JPanel();
	private Point lastPos = null;
	private Button captureButton = new Button("Capture");
	private Graphics gc;
	Graphics2D imageG = null;

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.applet.Applet#init()
	 */
	@Override
	public void init() {
		// TODO Auto-generated method stub
		super.init();

		setSize(600, 200);

		image = new BufferedImage(getWidth(), getHeight(),
				BufferedImage.TYPE_INT_ARGB);

		// get the image Graphics object
		imageG = image.createGraphics();
		colorPanel.setLayout(new GridLayout());
		canvas.setSize(getWidth(), getHeight());

		captureButton.setSize(100, 50);
		getContentPane().add(captureButton);
		getContentPane().add(canvas, BorderLayout.CENTER);
		setVisible(true);

		// get the Graphics Context
		gc = canvas.getGraphics();
		canvas.setBackground(Color.GRAY);
		gc.setColor(Color.GRAY);
		gc.fillRect(0, 0, image.getWidth(), image.getHeight());
		gc.setColor(Color.BLACK);

		imageG.setBackground(Color.GRAY);
		imageG.setColor(Color.GRAY);
		imageG.fillRect(0, 0, image.getWidth(), image.getHeight());
		imageG.setColor(Color.BLACK);

		captureButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent a) {
				try {
					Container cp = getContentPane();
					final Component comp = cp.add(new JSplitPane(
							JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(
									new JTextArea()), new JScrollPane(
									new JTextArea())));
					// cp.add(canvas);

					File filetoSave = new File("c:\\temp\\test4.jpeg");

					// If the file does not exist or the user gives permission,
					// save image to file.

					ImageWriter writer = null;
					ImageOutputStream ios = null;

					try {
						// Obtain a writer based on the jpeg format.

						Iterator iter;
						iter = ImageIO.getImageWritersByFormatName("jpeg");

						// Validate existence of writer.

						if (!iter.hasNext()) {
							return;
						}

						// Extract writer.

						writer = (ImageWriter) iter.next();

						// Configure writer output destination.

						ios = ImageIO.createImageOutputStream(filetoSave);
						writer.setOutput(ios);

						// Set JPEG compression quality to 95%.

						ImageWriteParam iwp = writer.getDefaultWriteParam();
						iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
						iwp.setCompressionQuality(0.95f);

						// Write the image.

						writer.write(null, new IIOImage((BufferedImage) image,
								null, null), iwp);
					} catch (IOException e2) {
						e2.getMessage();
					} finally {
						try {
							// Cleanup.

							if (ios != null) {
								ios.flush();
								ios.close();
							}

							if (writer != null)
								writer.dispose();
						} catch (IOException e2) {
						}
					}

				} catch (Exception e) {
					System.err.println(e);
				}
			}
		});

		canvas.addMouseMotionListener(new MouseMotionListener() {
			public void mouseDragged(MouseEvent m) {
				// the mouse(pen) was dragged, so the pixels at coords found in
				// MouseEvent m must be updated with current color
				Point p = m.getPoint();
				gc.drawLine(lastPos.x, lastPos.y, p.x, p.y);
				imageG.drawLine(lastPos.x, lastPos.y, p.x, p.y);
				lastPos = p;
			}

			public void mouseMoved(MouseEvent m) {
			}
		});
		canvas.addMouseListener(new MouseListener() {
			public void mouseClicked(MouseEvent e) {
			}

			public void mousePressed(MouseEvent e) {
				lastPos = e.getPoint();
			}

			public void mouseReleased(MouseEvent e) {
				lastPos = null;
			}

			public void mouseEntered(MouseEvent e) {
			}

			public void mouseExited(MouseEvent e) {
			}
		});
	}

	/**
	 * 
	 */
	public SignatureCapture() {
	}

	public static void main(String[] args) {
		SignatureCapture p = new SignatureCapture();
	}
}

Taking Screen Shot in Java

/**
*
*/
package com.pos;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

/**
* @author Ashwin
*
*/
public class Screenshot {
public static void main(String[] args) throws Exception {
// make sure we have exactly two arguments,
// a waiting period and a file name
if (args.length != 2) {
System.err.println("Usage: java Screenshot "
+ "WAITSECONDS OUTFILE.png");
System.exit(1);
}
// check if file name is valid
String outFileName = args[1];
if (!outFileName.toLowerCase().endsWith(".png")) {
System.err.println("Error: output file name must "
+ "end with \".png\".");
System.exit(1);
}
// wait for a user-specified time
try {
long time = Long.parseLong(args[0]) * 1000L;
System.out.println("Waiting " + (time / 1000L) + " second(s)...");
Thread.sleep(time);
} catch (NumberFormatException nfe) {
System.err.println(args[0] + " does not seem to be a "
+ "valid number of seconds.");
System.exit(1);
}
// determine current screen size
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
Rectangle screenRect = new Rectangle(screenSize);
// create screen shot
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRect);
// save captured image to PNG file
ImageIO.write(image, "png", new File(outFileName));
// give feedback
System.out.println("Saved screen shot (" + image.getWidth() + " x "
+ image.getHeight() + " pixels) to file\"" + outFileName
+ "\".");
// use System.exit if the program hangs after writing the file;
// that's an old bug which got fixed only recently
// System.exit(0);
}
}

HTML Buttons as Tabs

Here is just a simple Implementation of HTML Buttons as tabs

DHTML Web Tab Control

<!--

// Tab Name | URL | * (Default Selected Tab)
var tabs = new Array
(
"MSDN|http://msdn.microsoft.com",
"CNN|http://www.cnn.com",
"NASA|http://www.nasa.gov",
"Google|http://www.google.com|*",
"Forbes|http://www.forbes.com"
);

// Align Tab: LEFT, CENTER, RIGHT
var tabAlign = "RIGHT";

/*********************************************/

function tabOnClick(ID)
{
var oElement = null;

for (var i = 0; i < tabs.length; i++)
{
oElement = document.getElementById(i);
oElement.className = "tabOff";
}

oElement = document.getElementById(ID);
oElement.className = "tabOn";

var tab = tabs[ID].split("|");
divTabFrame.innerHTML = "";

document.body.focus();
}

function tabLoad()
{
var HTML = "";

HTML += "

";
for (var i = 0; i < tabs.length; i++)
{
var tab = tabs[i].split("|");
HTML += " ";
}

divTabButtons.innerHTML = HTML;

for (var i = 0; i


Click Framework

Recently i was looking at some framework which can be of help to me in Java Web World that can create UI dynamically using component driven architecture. Most of the projects these days are Metadata Driven. When we talk about metadata driven UI we need some component like framework where we can map metadata to some component. I had work on heavyweights like JSF but i dont think it gives whole lots of control to user to do what ever a developer wants that easily. Then i have come across this wonderful click framework.

We started building an application (Around september 2008) using this framework to one of our client where we define just some metadata and while website is built dynamically. Click framework made that possible. And i’m really happy to see that click has now be incorporated into apache.

Three cheers to click.

Rico Provides the All Power Full Ajax Table

Hello All,

I’m really impressed the way RICO has revolutionized the way we render table. Tables means Header + Data + Footer. But rico has changed the idea we define a table. It made it Header + Footer + Dynamic JavaScript or a DataSource. It also added a very nice functionality of progressive downloading. I.e Data can be downloaded while scrolling. It mixes the powerful feature of Ajax with object oriented javascript to provide this solution

Here is the example

Rico.loadModule('LiveGridAjax','LiveGridMenu','greenHdg.css');
Rico.loadModule('LiveGridMenu');

Rico.onLoad( function() {
var buffer = new Rico.Buffer.AjaxXML('test.xml');
var opts = {
useUnformattedColWidth: false,
defaultWidth : 90,
visibleRows : 'data',
frozenColumns: 1,
canPrint: false,
highltOnMouseOver: true,
rowHighlightColor: '#c4c4c5',
specFilterSort: {type:'raw', canSort:true, canFilter:true, quotes:"'"},
specFilter: {type:'raw', canSort:false, canFilter:true, quotes:"'"},
specSort: {type:'raw', canSort:true, canFilter:false, quotes:"'"},
columnSpecs : ['specSort','specFilterSort','specSort','specSort','specFilterSort']
};
var grid = new Rico.LiveGrid('data_grid', buffer, opts);
grid.menu=new Rico.GridMenu();

});

Now Sample Data can be some thing like this

5 Star Wars Action 9.0 135001 1977 6 The Lord of the Rings: The Two Towers Action 9.0 115175 2002 7 Star Wars: Episode V - The Empire Strikes Back Action 9.0 104167 1980 5 Star Wars Action 9.0 135001 1977 6 The Lord of the Rings: The Two Towers Action 9.0 115175 2002 7 Star Wars: Episode V - The Empire Strikes Back Action 9.0 104167 1980

Rico Has Lots of Functionalitites which add dynamic Sorting Searching features to you your grid without you explicitly handling those features in UI. Only thing we have toi write is code to render data and filter data. Rico takes care of rest

Enjoy RICO at http://openrico.org/
It has got a live grid which is of a lot of help in many projects.