Friday, October 17, 2008

Sending Mail through JavaAPI.

Hi Technos.,
Hope the java jambavans are aware of sending mail through Java API. Hope this could be helpful to the beginners who are not aware of sending mail through Java program. I will also list out a java program written by me and was well executed. JavaAPI is needed to send the mail through Java. You can download the JavaAPI by clicking here. Also if you are using the latest JDk1.6 there is no need of downloading JavaBeans Activation Framework(JAF) as it was bundled with the JDK1.6. Else you can download from here. Unzip the zip file the JavaMail API and extract the mail.jar from it and place it directly under 'lib' folder of the JDK installation directory. Also unzip the JAF zip file and extract the 'activation.jar' under the lib folder of the JDK installation directory. Make reference of both these jar file under the classpath environment variable. I here with providing you the following sample program to send mail with attachment

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.io.*;
import java.util.Date;

class SendMail
{
public static void main(String[] args)
{
try
{

Properties mailprop = new Properties();
String host = "smtp";
String fromAddress = "testing@enpysoft.com";
String toAddress = "npselvan@gmail.com"; //the mail to whom it is to sent
String filename = "c://npselvan//invitation.tiff";
String subj = "Welcome to EnpySoft";
String content = "Hi Friends!,\n\This is a sample program of how to send mail to recipient with attachment.\n\nRegards,\npselvan.";

mailprop.put("mail.smtp.host",host);

Session session = Session.getInstance(mailprop,null);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromAddress));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(toAddress));
message.setSubject(subj);

MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(content);
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(filename);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());

Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);

message.setContent(mp);
message.setSentDate(new java.util.Date());
Transport.send(message);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Hope this post thread give you idea of how to send mail in java with attachment.

Regards,
npselvan

No comments: