Monday, March 16, 2009

Java : Simple java program to Send Email from Gmail with attachments using JavaMail API

Java offers an API called Java Mail API from where we can send emails from java program. This article describes how we can send email (Gmail) with attachments using Java.

To send message with attachment we need to create an email with javax.mail.Multipart
object which basically will contains the email text message and then add a file to the second block, which both of them is an object of avax.mail.internet.MimeBodyPart.
In this example we also use the javax.activation.FileDataSource.


To run this code u need to download Java Mail API and JavaBeans Activation Framework





/*Here is the complete tested code for SendMailGmail.java*/


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

public class SendMailGmail
{
public static void main(String[] args)
{
Properties props = new Properties();
props.put("mail.smtp.user","madan712@gmail.com");

props.put("mail.smtp.host","smtp.gmail.com");

props.put("mail.smtp.port","465");

props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.debug","false");

props.put("mail.smtp.socketFactory.port","465");

props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");

try
{
Session session = Session.getDefaultInstance(props,null);
session.setDebug(true);

MimeMessage msg = new MimeMessage(session);
msg.setSubject("Java Mail");

Multipart multipart = new MimeMultipart();

MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("This Mail is send through Java API");

MimeBodyPart filePart = new MimeBodyPart();

FileDataSource fds = new FileDataSource("TextFile.txt");//file to attach
filePart.setDataHandler(new DataHandler(fds));
filePart.setFileName(fds.getName());

multipart.addBodyPart(textPart);
multipart.addBodyPart(filePart);

msg.setContent(multipart);

msg.setFrom(new InternetAddress("madan712@gmail.com"));

msg.addRecipient(Message.RecipientType.TO, new InternetAddress("madan@indiagames.com"));

msg.addRecipient(Message.RecipientType.CC, new InternetAddress("madan_chaudhary@rediffmail.com"));

msg.saveChanges();

Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com","madan712@gmail.com","******");//password

transport.sendMessage(msg, msg.getAllRecipients());

transport.close();

}
catch (Exception ex)
{
System.out.println("Exception occured"+ex);
ex.printStackTrace();
}
}
}