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);
}
}

}

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);
}
}

Sending Mail In Java

Many people find it difficult sending mail from a program. This code shows how simple it is to send a mail from java Program.

package com.webaging.utils;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
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 MailClient {

public void sendMail(String mailServer, String from, String to,
String subject, String messageBody, String[] attachments)
throws MessagingException, AddressException {
// Setup mail server
Properties props = System.getProperties();
props.put(“mail.smtp.host”, mailServer);

// Get a mail session
Session session = Session.getDefaultInstance(props, null);

// Define a new mail message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);

// Create a message part to represent the body text
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(messageBody);

// use a MimeMultipart as we need to handle the file attachments
Multipart multipart = new MimeMultipart();

// add the message body to the mime message
multipart.addBodyPart(messageBodyPart);

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

// Put all message parts in the message
message.setContent(multipart);

// Send the message
Transport.send(message);

}

protected 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);
}
}

public static void main(String[] args) {
try {
MailClient client = new MailClient();
String server = “pop3.mydomain.com”;
String from = “myname@mydomain.com”;
String to = “someuser@somewhere.com”;
String subject = “Test”;
String message = “Testing”;
String[] filenames = { “c:\\somefile.txt” };

client.sendMail(server, from, to, subject, message, filenames);
} catch (Exception e) {
e.printStackTrace(System.out);
}

}
}

Courtesy: http://www.osix.net/modules/article/?id=39