Code snippet to send an image file either inline or as an attachment in java.
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
public class MailAttachment {
private void addAttachments() throws MessagingException {
/*
* Here the references are declared in the method, Generally they will
* be passed into this method where this method gets called
*/
Multipart multipart = new MimeMultipart();
String attachmentNames = new String();
/*
* Getting the Directory path where the attachment resides on the local
* system.
*/
ResourceBundle bundle = ResourceBundle.getBundle("name");
String attachmentDirectory = bundle.getString("name_of directory")
+ System.getProperty("file.separator");
StringBuilder strBuilder = new StringBuilder(50);
/*
* Here many attachments can be added using a loop, attachmentNames is a
* String having a value of different attachment file names that are
* comma separated
*/
if (!((attachmentNames == null) || (attachmentNames.trim().equals("")))) {
StringTokenizer tokenizer = new StringTokenizer(attachmentNames,
",");
BodyPart bodypart = null;
DataSource dataSource = null;
String currentFileName = null;
while (tokenizer.hasMoreTokens()) {
currentFileName = tokenizer.nextToken();
strBuilder.setLength(0);
strBuilder.append(attachmentDirectory);
strBuilder.append(currentFileName);
bodypart = new MimeBodyPart();
/*
* Note: All the headers are to set using addHeader method and
* not setHeader
*/
bodypart.addHeader("Content-Type", "text/html");
/*
* Here oracle finds in the generated html
* content and replaces this with image at run time
*/
bodypart.addHeader("Content-ID", "<" + currentFileName + ">");
// Creating DataSource for the file
dataSource = new FileDataSource(strBuilder.toString());
bodypart.setDataHandler(new DataHandler(dataSource));
bodypart.setFileName(currentFileName);
/*
* Options to set the file as an attachment or in line with the
* mail
*/
bodypart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(bodypart);
}
}
}
}