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("mail.smtp.host", host);
     properties.setProperty("mail.transport.protocol","smtp");
                      properties.setProperty("mail.smtp.starttls.enable","true");
     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");
               }
           });

     try{
        // 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) {
        message.addRecipient(Message.RecipientType.TO,
                             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
        multipart.addBodyPart(messageBodyPart);

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

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

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





}