JavaMail Tutorialshttps://admin-api.codejava.net/java-ee/javamailWed, 24 Apr 2024 04:24:25 -0500Joomla! - Open Source Content Managementen-gbJavaMail - How to send e-mail with attachmentshttps://admin-api.codejava.net/java-ee/javamail/send-e-mail-with-attachment-in-javahttps://admin-api.codejava.net/java-ee/javamail/send-e-mail-with-attachment-in-java

This article provides a step-by-step guide on how to add attachments to an e-mail message to be sent via a SMTP server, using the JavaMail API. To understand how attachments are stored inside an e-mail message, let’s take a look at the following picture:

e-mail message structure

As we can see, a message comprises of a header and a body. The body must be of type Multipartfor containing attachments. The Multipart object holds multiple parts in which each part is represented as a type of BodyPart whose subclass, MimeBodyPart – can take a file as its content.

The steps to create a multipart message with multiple parts are as follows:

Message message = new MimeMessage(session);
Multipart multipart = new MimeMultipart();

// creates body part for the message
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");

// creates body part for the attachment
MimeBodyPart attachPart = new MimeBodyPart();

// code to add attachment...will be revealed later

// adds parts to the multipart
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachPart);

// sets the multipart as message's content
message.setContent(multipart);

 

The MimeBodyPart class provides some convenient methods for attaching a file, but the way is different between JavaMail 1.3 and JavaMail 1.4.

With JavaMail 1.3, it requires writing the following code to add an attachment:

// JavaMail 1.3
MimeBodyPart attachPart = new MimeBodyPart();
String attachFile = "D:/Documents/MyFile.mp4";

DataSource source = new FileDataSource(attachFile);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName(new File(attachFile).getName());

multipart.addBodyPart(attachPart);

 

With JavaMail 1.4, adding an attachment is much simpler with the following new methods introduced in the MimeBodyPart class:

  •            void attachFile(File file)
  •            void attachFile(String filePath)

So the code with JavaMail 1.4 would look like this:

// JavaMail 1.4
MimeBodyPart attachPart = new MimeBodyPart();
String attachFile = "D:/Documents/MyFile.mp4";
attachPart.attachFile(attachFile);
multipart.addBodyPart(attachPart);

The code for JavaMail 1.3 still works in 1.4.

Now for a sample program, the following class, EmailAttachmentSender – implements a static method, sendEmailWithAttachments() – which can be used for sending an e-mail message with some attachments. This method requires the following parameters:

  •            For SMTP server information: host, port number, user name (e-mail address), and password.
  •            For e-mail message: recipient e-mail address, subject, and message.
  •            For attached files: an array of String for file paths.

Here is the code of the class EmailAttachmentSender:

package net.codejava.mail;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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;

public class EmailAttachmentSender {

	public static void sendEmailWithAttachments(String host, String port,
			final String userName, final String password, String toAddress,
			String subject, String message, String[] attachFiles)
			throws AddressException, MessagingException {
		// sets SMTP server properties
		Properties properties = new Properties();
		properties.put("mail.smtp.host", host);
		properties.put("mail.smtp.port", port);
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.user", userName);
		properties.put("mail.password", password);

		// creates a new session with an authenticator
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(userName, password);
			}
		};
		Session session = Session.getInstance(properties, auth);

		// creates a new e-mail message
		Message msg = new MimeMessage(session);

		msg.setFrom(new InternetAddress(userName));
		InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
		msg.setRecipients(Message.RecipientType.TO, toAddresses);
		msg.setSubject(subject);
		msg.setSentDate(new Date());

		// creates message part
		MimeBodyPart messageBodyPart = new MimeBodyPart();
		messageBodyPart.setContent(message, "text/html");

		// creates multi-part
		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(messageBodyPart);

		// adds attachments
		if (attachFiles != null && attachFiles.length > 0) {
			for (String filePath : attachFiles) {
				MimeBodyPart attachPart = new MimeBodyPart();

				try {
					attachPart.attachFile(filePath);
				} catch (IOException ex) {
					ex.printStackTrace();
				}

				multipart.addBodyPart(attachPart);
			}
		}

		// sets the multi-part as e-mail's content
		msg.setContent(multipart);

		// sends the e-mail
		Transport.send(msg);

	}

	/**
	 * Test sending e-mail with attachments
	 */
	public static void main(String[] args) {
		// SMTP info
		String host = "smtp.gmail.com";
		String port = "587";
		String mailFrom = "your-email-address";
		String password = "your-email-password";

		// message info
		String mailTo = "your-friend-email";
		String subject = "New email with attachments";
		String message = "I have some attachments for you.";

		// attachments
		String[] attachFiles = new String[3];
		attachFiles[0] = "e:/Test/Picture.png";
		attachFiles[1] = "e:/Test/Music.mp3";
		attachFiles[2] = "e:/Test/Video.mp4";

		try {
			sendEmailWithAttachments(host, port, mailFrom, password, mailTo,
				subject, message, attachFiles);
			System.out.println("Email sent.");
		} catch (Exception ex) {
			System.out.println("Could not send email.");
			ex.printStackTrace();
		}
	}
}

 

NOTES:

You need to use JavaMail jar files. If you use Maven, add the following dependency to the pom.xml file:

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

This will add the javax.mail-VERSION.jar and activation-VERSION.jar to the project's classpath. If you have to add them manually, download from JavaMail Project page.

For Swing-based version of the sample program, see this tutorial: Swing application for sending e-mail (with attachments).

 

Other JavaMail Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)JavaMailThu, 29 Mar 2012 09:37:18 -0500
JavaMail - How to download attachments in e-mailshttps://admin-api.codejava.net/java-ee/javamail/get-attachments-in-e-mail-messages-using-javamailhttps://admin-api.codejava.net/java-ee/javamail/get-attachments-in-e-mail-messages-using-javamail

In this tutorial, I will guide you how to write Java code to download attachments from emails programmatically, using JavaMail API.

The article Receive e-mail messages from a POP3-IMAP server describes necessary steps to download e-mail messages from mail server, but only basic information of a message is retrieved, such as header fields (from, to, cc, subject…) and body message. However, the attachment is skipped. So this article is a complement which focuses on how to download attachments in an e-mail message.

A message may contain one or several attachments. As discussed in the article Send e-mail with attachment in Java, if a message contains attachments, its content must be of type MultiPart, and the part contains a file must be of type MimeBodyPart. So it’s important to determine if a message may contain attachments using the following code:

// suppose 'message' is an object of type Message
String contentType = message.getContentType();

if (contentType.contains("multipart")) {
	// this message may contain attachment
}

Then we must iterate through each part in the multipart to identify which part contains the attachment, as follows:

Multipart multiPart = (Multipart) message.getContent();

for (int i = 0; i < multiPart.getCount(); i++) {
	MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
	if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
		// this part is attachment
		// code to save attachment...
	}
}

The MimeBodyPart class provides methods for retrieving and storing attached file, but the way is different between JavaMail 1.3 and JavaMail 1.4.

In JavaMail 1.3, we have to read bytes from an InputStream which can be obtained from the method getInputStream() of the class MimeBodyPart, and write those bytes into an OutputStream, for example:

// save an attachment from a MimeBodyPart to a file
String destFilePath = "D:/Attachment/" + part.getFileName();

FileOutputStream output = new FileOutputStream(destFilePath);

InputStream input = part.getInputStream();

byte[] buffer = new byte[4096];

int byteRead;

while ((byteRead = input.read(buffer)) != -1) {
	output.write(buffer, 0, byteRead);
}
output.close(); 

In JavaMail 1.4, the MimeBodyPart class introduces two convenient methods that save us a lot of time:

-          void saveFile(File file)

-          void saveFile(String file)

So saving attachment from a part to a file is as easy as:

part.saveFile("D:/Attachment/" + part.getFileName());

 

or:

part.saveFile(new File(part.getFileName()));

 

And following is code of sample program that connects to a mail server via POP3 protocol, downloads new messages and save attachments to files on disk, if any. And it follows JavaMail 1.4 approach:

package net.codejava.mail;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.MimeBodyPart;

/**
 * This program demonstrates how to download e-mail messages and save
 * attachments into files on disk.
 *
 * @author www.codejava.net
 *
 */
public class EmailAttachmentReceiver {
	private String saveDirectory;

	/**
	 * Sets the directory where attached files will be stored.
	 * @param dir absolute path of the directory
	 */
	public void setSaveDirectory(String dir) {
		this.saveDirectory = dir;
	}

	/**
	 * Downloads new messages and saves attachments to disk if any.
	 * @param host
	 * @param port
	 * @param userName
	 * @param password
	 */
	public void downloadEmailAttachments(String host, String port,
			String userName, String password) {
		Properties properties = new Properties();

		// server setting
		properties.put("mail.pop3.host", host);
		properties.put("mail.pop3.port", port);

		// SSL setting
		properties.setProperty("mail.pop3.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		properties.setProperty("mail.pop3.socketFactory.fallback", "false");
		properties.setProperty("mail.pop3.socketFactory.port",
				String.valueOf(port));

		Session session = Session.getDefaultInstance(properties);

		try {
			// connects to the message store
			Store store = session.getStore("pop3");
			store.connect(userName, password);

			// opens the inbox folder
			Folder folderInbox = store.getFolder("INBOX");
			folderInbox.open(Folder.READ_ONLY);

			// fetches new messages from server
			Message[] arrayMessages = folderInbox.getMessages();

			for (int i = 0; i < arrayMessages.length; i++) {
				Message message = arrayMessages[i];
				Address[] fromAddress = message.getFrom();
				String from = fromAddress[0].toString();
				String subject = message.getSubject();
				String sentDate = message.getSentDate().toString();

				String contentType = message.getContentType();
				String messageContent = "";

				// store attachment file name, separated by comma
				String attachFiles = "";

				if (contentType.contains("multipart")) {
					// content may contain attachments
					Multipart multiPart = (Multipart) message.getContent();
					int numberOfParts = multiPart.getCount();
					for (int partCount = 0; partCount < numberOfParts; partCount++) {
						MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
						if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
							// this part is attachment
							String fileName = part.getFileName();
							attachFiles += fileName + ", ";
							part.saveFile(saveDirectory + File.separator + fileName);
						} else {
							// this part may be the message content
							messageContent = part.getContent().toString();
						}
					}

					if (attachFiles.length() > 1) {
						attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
					}
				} else if (contentType.contains("text/plain")
						|| contentType.contains("text/html")) {
					Object content = message.getContent();
					if (content != null) {
						messageContent = content.toString();
					}
				}

				// print out details of each message
				System.out.println("Message #" + (i + 1) + ":");
				System.out.println("\t From: " + from);
				System.out.println("\t Subject: " + subject);
				System.out.println("\t Sent Date: " + sentDate);
				System.out.println("\t Message: " + messageContent);
				System.out.println("\t Attachments: " + attachFiles);
			}

			// disconnect
			folderInbox.close(false);
			store.close();
		} catch (NoSuchProviderException ex) {
			System.out.println("No provider for pop3.");
			ex.printStackTrace();
		} catch (MessagingException ex) {
			System.out.println("Could not connect to the message store");
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * Runs this program with Gmail POP3 server
	 */
	public static void main(String[] args) {
		String host = "pop.gmail.com";
		String port = "995";
		String userName = "your_email";
		String password = "your_password";

		String saveDirectory = "E:/Attachment";

		EmailAttachmentReceiver receiver = new EmailAttachmentReceiver();
		receiver.setSaveDirectory(saveDirectory);
		receiver.downloadEmailAttachments(host, port, userName, password);

	}
} 

The program above will save attachments into a specified directory, and print out details of each received message, including file names of the attachments.

 

NOTES:

You need to use JavaMail jar files. If you use Maven, add the following dependency to the pom.xml file:

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

This will add the javax.mail-VERSION.jar and activation-VERSION.jar to the project's classpath. If you have to add them manually, download from JavaMail Project page.

 

Other JavaMail Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)JavaMailSun, 18 Nov 2012 09:48:17 -0600
JavaMail - How to send e-mail in HTML formathttps://admin-api.codejava.net/java-ee/javamail/send-e-mail-in-html-format-using-javamail-apihttps://admin-api.codejava.net/java-ee/javamail/send-e-mail-in-html-format-using-javamail-api

In the post Send e-mail in plain text using JavaMail, you know how to send an e-mail in plain text format. Although tt is possible to add HTML tags to the email's body content, that isn't enough to make the e-mail interpreted as an HTML e-mail in a web mail or an e-mail client program. So, instead of using:

Message msg = new MimeMessage(session);
msg.setText(message);

we should invoke the setContent(Object obj, String type) method of the MimeMessage object. The setContent() method specifies the mime type of the content explicitly, and for HTML format, the type parameter must be "text/html":

Message msg = new MimeMessage(session);
msg.setContent(message, "text/html");

That makes the difference! And following is source code of a sample program:

package net.codejava.mail;

import java.util.Date;
import java.util.Properties;

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

public class HtmlEmailSender {

	public void sendHtmlEmail(String host, String port,
			final String userName, final String password, String toAddress,
			String subject, String message) throws AddressException,
			MessagingException {

		// sets SMTP server properties
		Properties properties = new Properties();
		properties.put("mail.smtp.host", host);
		properties.put("mail.smtp.port", port);
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.starttls.enable", "true");

		// creates a new session with an authenticator
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(userName, password);
			}
		};

		Session session = Session.getInstance(properties, auth);

		// creates a new e-mail message
		Message msg = new MimeMessage(session);

		msg.setFrom(new InternetAddress(userName));
		InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
		msg.setRecipients(Message.RecipientType.TO, toAddresses);
		msg.setSubject(subject);
		msg.setSentDate(new Date());
		// set plain text message
		msg.setContent(message, "text/html");

		// sends the e-mail
		Transport.send(msg);

	}

	/**
	 * Test the send html e-mail method
	 *
	 */
	public static void main(String[] args) {
		// SMTP server information
		String host = "smtp.gmail.com";
		String port = "587";
		String mailFrom = "your-email-address";
		String password = "your-email-password";

		// outgoing message information
		String mailTo = "your-friend-email-address";
		String subject = "Hello my friend";

		// message contains HTML markups
		String message = "<i>Greetings!</i><br>";
		message += "<b>Wish you a nice day!</b><br>";
		message += "<font color=red>Duke</font>";

		HtmlEmailSender mailer = new HtmlEmailSender();

		try {
			mailer.sendHtmlEmail(host, port, mailFrom, password, mailTo,
					subject, message);
			System.out.println("Email sent.");
		} catch (Exception ex) {
			System.out.println("Failed to sent email.");
			ex.printStackTrace();
		}
	}
}

 

In a mail client like Outlook, the e-mail would look like the following screenshot:

html email message

NOTES:

You need to use JavaMail jar files. If you use Maven, add the following dependency to the pom.xml file:

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

This will add the javax.mail-VERSION.jar and activation-VERSION.jar to the project's classpath. If you have to add them manually, download from JavaMail Project page.

 

Other JavaMail Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)JavaMailThu, 29 Mar 2012 09:32:49 -0500
JavaMail - How to insert images into email for sendinghttps://admin-api.codejava.net/java-ee/javamail/embedding-images-into-e-mail-with-javamailhttps://admin-api.codejava.net/java-ee/javamail/embedding-images-into-e-mail-with-javamail

In the tutorial Send e-mail with attachment in Java, we discussed how to attach files to an e-mail message using JavaMail. In this article, we will use a similar technique plus some modification in order to embed some images directly into the message. The embedded images are called inline attachments which users see the images right inside the e-mail’s content. That’s different with regular attachments which the users have to download and open them manually.

The message must in HTML format in order to have inline images, so we should set content type of the message as follows:

MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(htmlMessage, "text/html");

Where htmlMessage is a String represents content of the message with HTML tags:

String htmlMessage = "<html>Hi there,<br>";
htmlMessage += "See this cool pic: <img src=\"cid:AbcXyz123\" />";
htmlMessage += "</html>";

As you notice in the HTML code above, we use the <img> tag to include an image, but its src attribute does not point to name of the image. Instead, the src attribute must refer to Content-ID header’s value of a MIME part which contains the actual image, in the following form:

src=”cid:<content_id>

Then the image part should be created as follows:

MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setHeader("Content-ID", "AbcXyz123");
imagePart.setDisposition(MimeBodyPart.INLINE);
// attach the image file
imagePart.attachFile(imageFilePath);

The value of the Content-ID header must be a unique identifier. This convention is described in the RFC 2387.

Now let’s create a real example with a utility class and a test program.

 

1. Coding An Email Utility class

We create an out-of-the-box utility class as follows:

package net.codejava.mail;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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;

/**
 * This utility class provides a functionality to send an HTML e-mail message
 * with embedded images.
 * @author www.codejava.net
 *
 */
public class EmbeddedImageEmailUtil {

	/**
	 * Sends an HTML e-mail with inline images.
	 * @param host SMTP host
	 * @param port SMTP port
	 * @param userName e-mail address of the sender's account 
	 * @param password password of the sender's account
	 * @param toAddress e-mail address of the recipient
	 * @param subject e-mail subject
	 * @param htmlBody e-mail content with HTML tags
	 * @param mapInlineImages 
	 * 			key: Content-ID
	 * 			value: path of the image file
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public static void send(String host, String port,
			final String userName, final String password, String toAddress,
			String subject, String htmlBody, 
			Map<String, String> mapInlineImages)
				throws AddressException, MessagingException {
		// sets SMTP server properties
		Properties properties = new Properties();
		properties.put("mail.smtp.host", host);
		properties.put("mail.smtp.port", port);
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("mail.user", userName);
		properties.put("mail.password", password);

		// creates a new session with an authenticator
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(userName, password);
			}
		};
		Session session = Session.getInstance(properties, auth);

		// creates a new e-mail message
		Message msg = new MimeMessage(session);

		msg.setFrom(new InternetAddress(userName));
		InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
		msg.setRecipients(Message.RecipientType.TO, toAddresses);
		msg.setSubject(subject);
		msg.setSentDate(new Date());

		// creates message part
		MimeBodyPart messageBodyPart = new MimeBodyPart();
		messageBodyPart.setContent(htmlBody, "text/html");

		// creates multi-part
		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(messageBodyPart);

		// adds inline image attachments
		if (mapInlineImages != null && mapInlineImages.size() > 0) {
			Set<String> setImageID = mapInlineImages.keySet();
			
			for (String contentId : setImageID) {
				MimeBodyPart imagePart = new MimeBodyPart();
				imagePart.setHeader("Content-ID", "<" + contentId + ">");
				imagePart.setDisposition(MimeBodyPart.INLINE);
				
				String imageFilePath = mapInlineImages.get(contentId);
				try {
					imagePart.attachFile(imageFilePath);
				} catch (IOException ex) {
					ex.printStackTrace();
				}

				multipart.addBodyPart(imagePart);
			}
		}

		msg.setContent(multipart);

		Transport.send(msg);
	}
}

Clients can call the static method send() to send an e-mail message in HTML format with embedded images passed via the parameter mapInlineImages. So it’s convenient for embedding an image as follows:

Map<String, String> inlineImages = new HashMap<String, String>();
inlineImages.put("ID123456", "D:/Images/stockchart.jpg");

Note this line:

imagePart.setHeader("Content-ID", "<" + contentId + ">");

The reason that we have to wrap the contentIdbetween the “<” and “>” is because some e-mail clients (such as Gmail) won’t show the inline images without those angle brackets.

 

2. Coding A Test program for embedding images into emails

Code the test program as follows:

package net.codejava.mail;

import java.util.HashMap;
import java.util.Map;

/**
 * This program tests out the EmbeddedImageEmailUtil utility class.
 * @author www.codejava.net
 *
 */
public class InlineImageEmailTester {

	/**
	 * main entry of the program
	 */
	public static void main(String[] args) {
		// SMTP info
		String host = "smtp.gmail.com";
		String port = "587";
		String mailFrom = "YOUR_EMAIL";
		String password = "YOUR_PASSWORD";

		// message info
		String mailTo = "YOUR_RECIPIENT";
		String subject = "Test e-mail with inline images";
		StringBuffer body
			= new StringBuffer("<html>This message contains two inline images.<br>");
		body.append("The first image is a chart:<br>");
		body.append("<img src=\"cid:image1\" width=\"30%\" height=\"30%\" /><br>");
		body.append("The second one is a cube:<br>");
		body.append("<img src=\"cid:image2\" width=\"15%\" height=\"15%\" /><br>");
		body.append("End of message.");
		body.append("</html>");

		// inline images
		Map<String, String> inlineImages = new HashMap<String, String>();
		inlineImages.put("image1", "E:/Test/chart.png");
		inlineImages.put("image2", "E:/Test/cube.jpg");

		try {
			EmbeddedImageEmailUtil.send(host, port, mailFrom, password, mailTo,
				subject, body.toString(), inlineImages);
			System.out.println("Email sent.");
		} catch (Exception ex) {
			System.out.println("Could not send email.");
			ex.printStackTrace();
		}
	}
}

 

In this test program, we configure SMTP settings for a GMail account and compose an HTML message with two inline images image1 and image2 which correspond to two actual images file chart.png and cube.jpg.

When running this program, we got the following result in GMail:

email embedded images in GMail

And in Microsoft Outlook:

email embedded images in Outlook

 

NOTES:

You need to use JavaMail jar files. If you use Maven, add the following dependency to the pom.xml file:

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

This will add the javax.mail-VERSION.jar and activation-VERSION.jar to the project's classpath. If you have to add them manually, download from JavaMail Project page.

 

Other JavaMail Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)JavaMailFri, 28 Dec 2012 10:47:42 -0600
JavaMail - How to search e-mail messageshttps://admin-api.codejava.net/java-ee/javamail/using-javamail-for-searching-e-mail-messageshttps://admin-api.codejava.net/java-ee/javamail/using-javamail-for-searching-e-mail-messages

The JavaMail API allows developers writing code for searching e-mail messages within user’s inbox. This can be accomplished by calling the search() function which is provided by the Folderclass:

 

Message[] search(SearchTerm term)

 

This method returns an array of Message objects which match a search criterion specified by a subclass of SearchTerm class. We need to create a class that extends from SearchTerm class and overrides its method match(). For example:

SearchTerm term = new SearchTerm() {
	public boolean match(Message message) {
		try {
			if (message.getSubject().contains("Java")) {
				return true;
			}
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
		return false;
	}
};

 

As we can see, the match() method above returns true if a message with subject containing the word “Java”. In other words, the search term above will match all messages having the word “Java” in its Subject field. And pass this new SearchTerm object to the search method as follows:

Message[] foundMessages = folder.search(term);

 

The search() method returns an empty array if no matches were found. Subclasses of Folder class implements this search functionality for corresponding protocol, i.e IMAPFolder class and POP3Folder class.

The following program connects to a mail server via IMAP protocol and searches for all messages containing the word “JavaMail” in the Subject field, within the inbox folder. Here is the code:

package net.codejava.mail;

import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.SearchTerm;

/**
 * This program demonstrates how to search for e-mail messages which satisfy
 * a search criterion.
 * @author www.codejava.net
 *
 */
public class EmailSearcher {

	/**
	 * Searches for e-mail messages containing the specified keyword in
	 * Subject field.
	 * @param host
	 * @param port
	 * @param userName
	 * @param password
	 * @param keyword
	 */
	public void searchEmail(String host, String port, String userName,
			String password, final String keyword) {
		Properties properties = new Properties();

		// server setting
		properties.put("mail.imap.host", host);
		properties.put("mail.imap.port", port);

		// SSL setting
		properties.setProperty("mail.imap.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		properties.setProperty("mail.imap.socketFactory.fallback", "false");
		properties.setProperty("mail.imap.socketFactory.port",
				String.valueOf(port));

		Session session = Session.getDefaultInstance(properties);

		try {
			// connects to the message store
			Store store = session.getStore("imap");
			store.connect(userName, password);

			// opens the inbox folder
			Folder folderInbox = store.getFolder("INBOX");
			folderInbox.open(Folder.READ_ONLY);

			// creates a search criterion
			SearchTerm searchCondition = new SearchTerm() {
				@Override
				public boolean match(Message message) {
					try {
						if (message.getSubject().contains(keyword)) {
							return true;
						}
					} catch (MessagingException ex) {
						ex.printStackTrace();
					}
					return false;
				}
			};

			// performs search through the folder
			Message[] foundMessages = folderInbox.search(searchCondition);

			for (int i = 0; i < foundMessages.length; i++) {
				Message message = foundMessages[i];
				String subject = message.getSubject();
				System.out.println("Found message #" + i + ": " + subject);
			}

			// disconnect
			folderInbox.close(false);
			store.close();
		} catch (NoSuchProviderException ex) {
			System.out.println("No provider.");
			ex.printStackTrace();
		} catch (MessagingException ex) {
			System.out.println("Could not connect to the message store.");
			ex.printStackTrace();
		}
	}

	/**
	 * Test this program with a Gmail's account
	 */
	public static void main(String[] args) {
		String host = "imap.gmail.com";
		String port = "993";
		String userName = "your_email";
		String password = "your_password";
		EmailSearcher searcher = new EmailSearcher();
		String keyword = "JavaMail";
		searcher.searchEmail(host, port, userName, password, keyword);
	}

}

 

We can combine multiple properties of a Message object to create more complex search criterion, for example:

if (message.getSubject().contains(keyword)
		&& message.getSentDate().after(aDate)) {
	return true;
}

 

Following are some useful search criteria:

Search criterion for From field:

package net.codejava.mail;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.search.SearchTerm;

public class FromFieldSearchTerm extends SearchTerm {
	private String fromEmail;
	
	public FromFieldSearchTerm(String fromEmail) {
		this.fromEmail = fromEmail;
	}
	
	@Override
	public boolean match(Message message) {
		try {
			Address[] fromAddress = message.getFrom();
			if (fromAddress != null && fromAddress.length > 0) {
				if (fromAddress[0].toString().contains(fromEmail)) {
					return true;
				}
			}
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
		
		return false;
	}
	
} 

 

Search criterion for Sent Date field:

package net.codejava.mail;

import java.util.Date;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.search.SearchTerm;

public class SentDateSearchTerm extends SearchTerm {
	private Date afterDate;
	
	public SentDateSearchTerm(Date afterDate) {
		this.afterDate = afterDate;
	}
	
	@Override
	public boolean match(Message message) {
		try {
			if (message.getSentDate().after(afterDate)) {
				return true;
			}
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
		return false;
	}

} 

 

Search criterion for message content:

package net.codejava.mail;

import java.io.IOException;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.search.SearchTerm;

public class ContentSearchTerm extends SearchTerm {
	private String content;
	
	public ContentSearchTerm(String content) {
		this.content = content;
	}
	
	@Override
	public boolean match(Message message) {
		try {
			String contentType = message.getContentType().toLowerCase();
			if (contentType.contains("text/plain")
					|| contentType.contains("text/html")) {
				String messageContent = message.getContent().toString();
				if (messageContent.contains(content)) {
					return true;
				}
			}
		} catch (MessagingException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return false;
	}

}

 

NOTES:

You need to use JavaMail jar files. If you use Maven, add the following dependency to the pom.xml file:

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

This will add the javax.mail-VERSION.jar and activation-VERSION.jar to the project's classpath. If you have to add them manually, download from JavaMail Project page.

 

Other JavaMail Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)JavaMailTue, 20 Nov 2012 09:06:51 -0600
How to receive emails from server using JavaMailhttps://admin-api.codejava.net/java-ee/javamail/receive-e-mail-messages-from-a-pop3-imap-serverhttps://admin-api.codejava.net/java-ee/javamail/receive-e-mail-messages-from-a-pop3-imap-server

This article walks through steps to download e-mail messages from a POP3/IMAP server’s inbox, using JavaMail API. The following picture depicts how messages are logically stored on the server:

mail store

we can see, for each user account, the server has a store which is the storage of user’s messages. The store is divided into folders, and the “inbox” folder is the primarily folder which contains e-mail messages. A folder can contain both messages and sub-folders.

Speaking of JavaMail API‘s language, it provides three corresponding classes: Store, Folder and Message.

-          A Store object can be obtained from the current session by invoking the method getStore(String protocol) of Session class. Connecting to the Store by calling its method connect(String user, String pass), disconnecting by calling its close() method.

-          A Folder object can be obtained from the store by invoking the getFolder(String folderName) method. For a regular mail box, the folder name must be “inbox” (case-insensitive). The most important methods of the Folder class are:

          • open(int mode): Opens the folder either in READ_ONLY mode or READ_WRITE mode.
          • getMessages(): Retrieves an array of Message objects which are marked un-read in the folder. A Message object may be a lightweight reference, and its detailed content will be filled up on demand.
          • close(boolean expunge): Closes the folder, and permanently remove all messages which are marked delete, if expunge is true.

-          A Message object represents an e-mail message. To get detailed attributes of a message, the following methods can be called on the Message object:

          • Address[] getFrom(): returns a list of senders in From attribute of the message.
          • Address[] getRecipients(Message.RecipientType type): gets recipient addresses of the message, type can be either TO or CC.
          • String getSubject(): gets subject of the message.
          • Date getSentDate(): gets date and time when the message was sent.
          • Object getContent(): gets content of the message.

Typically, the steps to connect to a server and download new e-mail messages are as follows:

-          Prepare a Properties object which holds server settings such as host, port, protocol…

-          Create a session to initiate a working session with the server.

-          Obtain a store from the session by a specific protocol (IMAP or POP3). IMAP is recommended.

-          Connect to the store using a credential (username and password).

-          Gets inbox folder from the store.

-          Open the inbox folder.

-          Retrieve messages from the folder.

-          Fetch details for each message.

-          Close the folder.

-          Close the store.

And following is code of a sample program:

package net.codejava.mail;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

/**
 * This program demonstrates how to get e-mail messages from a POP3/IMAP server
 *
 * @author www.codejava.net
 *
 */
public class EmailReceiver {

	/**
	 * Returns a Properties object which is configured for a POP3/IMAP server
	 *
	 * @param protocol either "imap" or "pop3"
	 * @param host
	 * @param port
	 * @return a Properties object
	 */
	private Properties getServerProperties(String protocol, String host,
			String port) {
		Properties properties = new Properties();

		// server setting
		properties.put(String.format("mail.%s.host", protocol), host);
		properties.put(String.format("mail.%s.port", protocol), port);

		// SSL setting
		properties.setProperty(
				String.format("mail.%s.socketFactory.class", protocol),
				"javax.net.ssl.SSLSocketFactory");
		properties.setProperty(
				String.format("mail.%s.socketFactory.fallback", protocol),
				"false");
		properties.setProperty(
				String.format("mail.%s.socketFactory.port", protocol),
				String.valueOf(port));

		return properties;
	}

	/**
	 * Downloads new messages and fetches details for each message.
	 * @param protocol
	 * @param host
	 * @param port
	 * @param userName
	 * @param password
	 */
	public void downloadEmails(String protocol, String host, String port,
			String userName, String password) {
		Properties properties = getServerProperties(protocol, host, port);
		Session session = Session.getDefaultInstance(properties);

		try {
			// connects to the message store
			Store store = session.getStore(protocol);
			store.connect(userName, password);

			// opens the inbox folder
			Folder folderInbox = store.getFolder("INBOX");
			folderInbox.open(Folder.READ_ONLY);

			// fetches new messages from server
			Message[] messages = folderInbox.getMessages();

			for (int i = 0; i < messages.length; i++) {
				Message msg = messages[i];
				Address[] fromAddress = msg.getFrom();
				String from = fromAddress[0].toString();
				String subject = msg.getSubject();
				String toList = parseAddresses(msg
						.getRecipients(RecipientType.TO));
				String ccList = parseAddresses(msg
						.getRecipients(RecipientType.CC));
				String sentDate = msg.getSentDate().toString();

				String contentType = msg.getContentType();
				String messageContent = "";

				if (contentType.contains("text/plain")
						|| contentType.contains("text/html")) {
					try {
						Object content = msg.getContent();
						if (content != null) {
							messageContent = content.toString();
						}
					} catch (Exception ex) {
						messageContent = "[Error downloading content]";
						ex.printStackTrace();
					}
				}

				// print out details of each message
				System.out.println("Message #" + (i + 1) + ":");
				System.out.println("\t From: " + from);
				System.out.println("\t To: " + toList);
				System.out.println("\t CC: " + ccList);
				System.out.println("\t Subject: " + subject);
				System.out.println("\t Sent Date: " + sentDate);
				System.out.println("\t Message: " + messageContent);
			}

			// disconnect
			folderInbox.close(false);
			store.close();
		} catch (NoSuchProviderException ex) {
			System.out.println("No provider for protocol: " + protocol);
			ex.printStackTrace();
		} catch (MessagingException ex) {
			System.out.println("Could not connect to the message store");
			ex.printStackTrace();
		}
	}

	/**
	 * Returns a list of addresses in String format separated by comma
	 *
	 * @param address an array of Address objects
	 * @return a string represents a list of addresses
	 */
	private String parseAddresses(Address[] address) {
		String listAddress = "";

		if (address != null) {
			for (int i = 0; i < address.length; i++) {
				listAddress += address[i].toString() + ", ";
			}
		}
		if (listAddress.length() > 1) {
			listAddress = listAddress.substring(0, listAddress.length() - 2);
		}

		return listAddress;
	}

	/**
	 * Test downloading e-mail messages
	 */
	public static void main(String[] args) {
		// for POP3
		//String protocol = "pop3";
		//String host = "pop.gmail.com";
		//String port = "995";

		// for IMAP
		String protocol = "imap";
		String host = "imap.gmail.com";
		String port = "993";


		String userName = "your_email_address";
		String password = "your_email_password";

		EmailReceiver receiver = new EmailReceiver();
		receiver.downloadEmails(protocol, host, port, userName, password);
	}
}

In the EmailReceiver class above, the primary method is downloadEmail(), and the two helper methods, getServerProperties() and parseAddresses(). The server information used for testing is Gmail’s IMAP server, and remember to change userName and password to match your account.

 

NOTES:

 

You need to use JavaMail jar files. If you use Maven, add the following dependency to the pom.xml file:

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

This will add the javax.mail-VERSION.jar and activation-VERSION.jar to the project's classpath. If you have to add them manually, download from JavaMail Project page.

 

 

Other JavaMail Tutorials:

 

]]>
hainatu@gmail.com (Nam Ha Minh)JavaMailFri, 16 Nov 2012 10:52:56 -0600
JavaMail - How to send e-mail in plain texthttps://admin-api.codejava.net/java-ee/javamail/send-e-mail-in-plain-text-using-javamailhttps://admin-api.codejava.net/java-ee/javamail/send-e-mail-in-plain-text-using-javamail

In this post, you will learn how to write Java code for sending plain text emails programmatically using JavaMail API.

First, you need to use JavaMail jar files. If you use Maven, add the following dependency to the pom.xml file:

This will add the javax.mail-VERSION.jar and activation-VERSION.jar to the project's classpath. If you have to add them manually, download from JavaMail Project page.

To send an e-mail in plain text using JavaMail, simply call the method setText(String)on the Message object. The following class, PlainTextEmailSender, implements a general method which sends a plain text e-mail message from a SMTP server. It requires supplying information of the SMTP server and the message:

  •             For SMTP server: host, port number, user name (e-mail address), and password.
  •             For e-mail message: recipient address, subject, and message.

Here is the code:

package net.codejava.mail;

import java.util.Date;
import java.util.Properties;

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

public class PlainTextEmailSender {

	public void sendPlainTextEmail(String host, String port,
			final String userName, final String password, String toAddress,
			String subject, String message) throws AddressException,
			MessagingException {

		// sets SMTP server properties
		Properties properties = new Properties();
		properties.put("mail.smtp.host", host);
		properties.put("mail.smtp.port", port);
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.starttls.enable", "true");

		// creates a new session with an authenticator
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(userName, password);
			}
		};

		Session session = Session.getInstance(properties, auth);

		// creates a new e-mail message
		Message msg = new MimeMessage(session);

		msg.setFrom(new InternetAddress(userName));
		InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
		msg.setRecipients(Message.RecipientType.TO, toAddresses);
		msg.setSubject(subject);
		msg.setSentDate(new Date());
		// set plain text message
		msg.setText(message);

		// sends the e-mail
		Transport.send(msg);

	}

	/**
	 * Test the send e-mail method
	 *
	 */
	public static void main(String[] args) {
		// SMTP server information
		String host = "smtp.gmail.com";
		String port = "587";
		String mailFrom = "user_email";
		String password = "email_pass";

		// outgoing message information
		String mailTo = "recipient_email";
		String subject = "Hello my friend";
		String message = "Hi guy, Hope you are doing well. Duke.";

		PlainTextEmailSender mailer = new PlainTextEmailSender();

		try {
			mailer.sendPlainTextEmail(host, port, mailFrom, password, mailTo,
					subject, message);
			System.out.println("Email sent.");
		} catch (Exception ex) {
			System.out.println("Failed to sent email.");
			ex.printStackTrace();
		}
	}
}

The SMTP server used in the program above is Gmail. Change mailFrom and password corresponding to your e-mail account.

 

Other JavaMail Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)JavaMailThu, 29 Mar 2012 09:30:36 -0500
JavaMail - How to delete email on mail server programmaticallyhttps://admin-api.codejava.net/java-ee/javamail/delete-e-mail-messages-on-mail-server-programmaticallyhttps://admin-api.codejava.net/java-ee/javamail/delete-e-mail-messages-on-mail-server-programmatically

In this post, I will guide you how to write Java code to delete emails on a mail server programmatically.

To send emails with Java, you need to use JavaMail jar files. If you use Maven, add the following dependency to the pom.xml file:

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

This will add the javax.mail-VERSION.jar and activation-VERSION.jar to the project's classpath. If you have to add them manually, download from JavaMail Project page.

To delete e-mail messages which are stored on mail server using JavaMail API, it requires following the steps below:

-          Open the inbox folder in READ_WRITE mode.

-          Retrieves messages from inbox folder (For more details, see the article Receive e-mail messages from a POP3-IMAP server).

-          Iterate through the received messages, if one needs to be delete, mark it as deleted by invoking the method setFlag(Flags.Flag.DELETED, true)on the Messageobject. For example: 

if (message.getSubject().contains("Promo")) {
	message.setFlag(Flags.Flag.DELETED, true);
}

 

-          The messages marked DELETED are not actually deleted, until we call the expunge() method on the Folder object, or close the folder with expunge set to true. For example:

boolean expunge = true;
folder.close(expunge);

      or:

folder.expunge();
folder.close(false);

 

 The following sample program demonstrates how to conditionally delete e-mail messages with subject field contains the word “Newsletter”:

package net.codejava.mail;

import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

/**
 * This program demonstrates how to remove e-mail messages on a mail server
 * using JavaMail API.
 * @author www.codejava.net
 *
 */
public class EmailMessageRemover {

	/**
	 * Deletes all e-mail messages whose subject field contain
	 * a string specified by 'subjectToDelete'
	 * @param host
	 * @param port
	 * @param userName
	 * @param password
	 * @param subjectToDelete delete if the message's subject contains this value.
	 */
	public void deleteMessages(String host, String port,
			String userName, String password, String subjectToDelete) {
		Properties properties = new Properties();

		// server setting
		properties.put("mail.imap.host", host);
		properties.put("mail.imap.port", port);

		// SSL setting
		properties.setProperty("mail.imap.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		properties.setProperty("mail.imap.socketFactory.fallback", "false");
		properties.setProperty("mail.imap.socketFactory.port",
				String.valueOf(port));

		Session session = Session.getDefaultInstance(properties);

		try {
			// connects to the message store
			Store store = session.getStore("imap");
			store.connect(userName, password);

			// opens the inbox folder
			Folder folderInbox = store.getFolder("INBOX");
			folderInbox.open(Folder.READ_WRITE);

			// fetches new messages from server
			Message[] arrayMessages = folderInbox.getMessages();

			for (int i = 0; i < arrayMessages.length; i++) {
				Message message = arrayMessages[i];
				String subject = message.getSubject();
				if (subject.contains(subjectToDelete)) {
					message.setFlag(Flags.Flag.DELETED, true);
					System.out.println("Marked DELETE for message: " + subject);
				}

			}

			// expunges the folder to remove messages which are marked deleted
			boolean expunge = true;
			folderInbox.close(expunge);

			// another way:
			//folderInbox.expunge();
			//folderInbox.close(false);

			// disconnect
			store.close();
		} catch (NoSuchProviderException ex) {
			System.out.println("No provider.");
			ex.printStackTrace();
		} catch (MessagingException ex) {
			System.out.println("Could not connect to the message store.");
			ex.printStackTrace();
		}
	}

	/**
	 * Runs this program to delete e-mail messages on a Gmail account
	 * via IMAP protocol.
	 */
	public static void main(String[] args) {
		String host = "imap.gmail.com";
		String port = "993";
		String userName = "your_email";
		String password = "your_password";
		EmailMessageRemover remover = new EmailMessageRemover();

		// try to delete all messages contain this string its Subject field
		String subjectToDelete = "Newsletter";
		remover.deleteMessages(host, port, userName, password, subjectToDelete);

	}
} 

The program above is tested with a Gmail account using IMAP protocol. Change value of userNameand password to match with your account.

 

Other JavaMail Tutorials:

]]>
hainatu@gmail.com (Nam Ha Minh)JavaMailMon, 19 Nov 2012 09:16:26 -0600
How to start e-mail programming in Javahttps://admin-api.codejava.net/java-ee/javamail/how-to-start-e-mail-programming-in-javahttps://admin-api.codejava.net/java-ee/javamail/how-to-start-e-mail-programming-in-java

You are a Java developer and would like to integrate e-mail functionality into your application, but you haven’t written anything related to e-mail stuff before. So here is a good place for getting started with e-mail programming in Java.

Like any other Java technologies, we need to pick up a library and understand its API before writing and testing some real code. Although the JRE/JDK does not include a built-in API for e-mail, Oracle provides an optional package called JavaMail which is probably the most popular framework for e-mail programming with Java technology. The JavaMail is also a part of JavaEE’s technology stack.

 

1. Official resources for JavaMail

Here are some official resources provided by Oracle for its JavaMail technology:

-          JavaMail Home page.

-          JavaMail Download page.

-          JavaMail Documentation.

-          JavaMail Specification.

To begin, download the latest distribution of JavaMail (which is JavaMail 1.6.2 at the time of writing this article). A JavaMail distribution comes with the following items:

-          License and copyright notices.

-          Release changes.

-          API documentation.

-          Demo Java source code.

-          Jar files for protocol-dependent implementation: imap.jar, pop3.jar, smtp.jar…

-          Binary of the JavaMail API included in mail.jar file. This jar file is a combination of all jar files above. So to use JavaMail, only the mail.jar file is required.

 

2. Using JavaMail library

To compile and run code that is using JavaMail, add the mail.jar file to compile classpath and runtime classpath.

If you are using Java 5 or earlier, you have to download the JavaBeans Activation Framework (JAF) and add activation.jar file to the classpath. The JAF is only included in JDK since Java 6.

If you use Maven, simply specify the following dependency for your project:

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.2</version>
</dependency>

 

3. Understanding of e-mail protocols: SMTP, IMAP and POP3

Because JavaMail is based on standard e-mail protocols like SMTP, IMAP, and POP3, it’s recommended to have basic understanding of how these protocols work, as well as advantages and disadvantages of each protocol. That would help you implement your code more efficiently. Here are the links for these protocols on Wikipedia:

-          Simple Mail Transfer Protocol.

-          Internet Message Access Protocol.

-          Post Office Protocol.

And finally, once you have grasped the stuff above, follow our series of tutorial on JavaMail technology:

]]>
hainatu@gmail.com (Nam Ha Minh)JavaMailWed, 21 Nov 2012 10:48:12 -0600