Monday, 9 March 2015

Send Mail in java Example

Send Mail

here is java program to send a mail to one or more recipients.

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail {

public boolean sendMail(String file,String camp,String recipients)

     String[] recipientsList=recipients.split(";");
     String to = "to_address";
     String from = "from_address";

        // Assuming you are sending email from localhost
         String host = "yoursmtpserver";
     // Get system properties
     Properties properties = System.getProperties();

     // Setup mail server
     properties.setProperty("", host);
     properties.put("mail.smtp.port", "587");
     properties.put("mail.smtp.auth", "true");
     properties.put("mail.debug", "true");
     // Get the default Session object.
     Session session = Session.getDefaultInstance(properties,new javax.mail.Authenticator() {
               protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication("from_address", "PASSWORD");

        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        for (String string : recipientsList) {
                             new InternetAddress(string));
        // Set Subject: header field
        message.setSubject("Subject Here");

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText("MSG Body");
        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = file;
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));

        // Send the complete message parts
        message.setContent(multipart );

        // Send message
        System.out.println("Sent message successfully....");
     }catch (MessagingException mex) {
return true;