Send Mail via java

//Require javamail-1.4.jar; commons-email-1.1.jar;
import java.util.*;
import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;

public class Mail {
public static void main(String []args) throws MessagingException
{
Mail m =new Mail();
}
    public Mail() throws MessagingException {

        String host = "smtp.gmail.com";
        String Password = "****";
        String from = "from@gmail.com";
        String toAddress = "to@gmail.com";
        String filename = "commons-io-1.0.zip";
        String filename1 = "path.java";
        // Get system properties
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtps.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        Session session = Session.getInstance(props, null);

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, toAddress);
        message.setRecipients(Message.RecipientType.TO, from);
        message.setSubject("");
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText("");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);
        message.setHeader("X-Priority", "1") ; 

        try {
            Transport tr = session.getTransport("smtps");
           
            tr.connect(host, from, Password);
            System.out.println("Password Verified");
           
            //tr.sendMessage(message, message.getAllRecipients());
            System.out.println("Mail Sent Successfully");
            tr.close();

        } catch (SendFailedException sfe) {

            System.out.println(sfe);
        }
    }
}

Comments