Sending Mail with attachment through JavaMail
Hi Folks,
In this article, am going to give you a sample program to send an email with attachment through JavaMail API in java program. You should have JavaMail and JavaBeans Activation Framework(if needed) to make work this program. JAF is needed when you have the JDK installed other than the version 1.6 or more. JAF is bundled with JDK1.6 and for those who use the older version can follow the download file reference link available here. JavaMail download reference link can be followed by clicking here. When you extract both these downloaded zip file, you can have the jar files named ‘activation.jar’(from JAF) and ‘mail.jar’(from JavaMail). Place these two jar files under the ‘lib’ folders of the JDK installation directory and also make the reference of these two jar files to the classpath environment variable.
I here with inline the java program to send mail with attachment.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class MailWithAttachment
{
public static void main(String[] args)
{
try
{
java.util.Properties mailprop = new java.util.Properties();
String host = "smtp";
String fromAddress = "test@enpysoft.com";
String toAddress = "muthuselvan@adventnet.com";
String filename = "c://npselvan//invitation.tiff";
String subj = "Invitation";
String content = "Hi Friends!,\n\tI cordially invite you all guys for the seminar.\n\nRegards,\nNpselvan.";
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 the above program could fetch idea to the beginners of Java.
Comments are Welcomed..!
No comments yet.
Leave a comment
-
Archives
- August 2009 (1)
- June 2009 (1)
- April 2009 (4)
- November 2008 (1)
- October 2008 (3)
- March 2008 (1)
- September 2007 (1)
- August 2007 (5)
- July 2007 (21)
-
Categories
-
RSS
Entries RSS
Comments RSS