Skip to Content

“A picture is worth a thousand words”

In the present world the mailing applications do much more than just sending across text messages. You come across instances requiring you to pass pictures or video clips across through the mail. I tried to work out a scenario of attaching a simple .jpeg file using JavaMail.

In JavaMail, a message can hold either a content or a Multipart. Multipart(javax.mail.Multipart) class can contain many blocks of javax.mail.BodyPart objects.

image

For attaching the file we make use of the javax.activation.DataHandler class and the javax.activation.FileDataSource class from the Java activation FrameWork.

The code for the mailing application is given below.

public class FirstMail {

public static void main(String[] args) {
try{
Properties props=new Properties();
props.put(“mail.transport.protocol”,”smtp”);
props.put(“mail.smtp.host”,ServerName);
props.put(“mail.smtp.port”,Port No);

Session session=Session.getInstance(props);

MimeMessage message=new MimeMessage(session);
Multipart mailContent=new MimeMultipart();
MimeBodyPart mailText=new MimeBodyPart();

Address from=new InternetAddress(from id);
Address toAddress = new InternetAddress(to address);

message.setFrom(from);
message.setRecipient(Message.RecipientType.TO,toAddress);

message.setSubject(“My Test”);

//setting the mail content

mailText.setText(“Test”);
mailContent.addBodyPart(mailText);

//attaching the picture

FileDataSource fds=new FileDataSource(the path of the file to be attached);
MimeBodyPart mmattch=new MimeBodyPart();
mmattch.setDataHandler(new DataHandler(fds));
mmattch.setFileName(fds.getName());
mailContent.addBodyPart(mmattch);
message.setContent(mailContent);

Transport.send(message);

}catch(Exception e){
System.out.println(e.toString());
}
}
}

The jar files mail.jar and activation.jar (C:\Program Files\SAP\JDT\eclipse\plugins\com.tssap.ext.libs.j2ee_1.3\lib) has to be included in the buildpath.

To report this post you need to login first.

3 Comments

You must be Logged on to comment or reply to a post.

Leave a Reply