Saturday, 6 February 2016

Java program to send mail using Gmail smtp with attachments

Requirements

1)javax mail jar file (javamail-1.4.5)

Gmail smtp need authentication so you must provide username and password

package emailblog;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;



    public class EmailSender {

    private static String SMTP_HOST_NAME = "smtp.gmail.com";
    private static String SMTP_PORT= "465";
    private static String SSL_FACTORY="javax.net.ssl.SSLSocketFactory";
    private static String emailContent = "success";
    private static String emailSubject = "subject email";
    private static String emailFromAddress="your email address";
    private static String emailPassword="your email password";
    private static final String[] attachment = {                              
            "attachmnt's file path",
            "attachmnt's file path" };                                 //attachmnt file address

    private static final String[] sendTo = { "to address" };               //to address
    private static final String[] sendCC = {"cc address"};                //cc address
    private static final String[] sendBCC = {"bcc address"};           //Bcc address
   
   

    public static void main(String[] args) throws Exception {

        EmailSender emailSender = new EmailSender();
       
        emailSender.sendMail(sendTo, sendCC, sendBCC, emailSubject,           
                emailContent, emailFromAddress, attachment);
    }                                                           //calling sendMail method for send mail

    private void sendMail(String[] toAddress, String[] ccAddress,
            String[] bccAddress, String subject, String message, String from,
            String[] attach) throws MessagingException {

        boolean debug = true;
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");

        Session session = Session.getDefaultInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(emailFromAddress,
                                emailPassword);
                    }

                });
        session.setDebug(debug);
        Message msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();  //creating object for multipart
     
       MimeBodyPart messageBodyPart = new MimeBodyPart();       //creating first obj for bodypart to send msg

        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[toAddress.length];
        for (int i = 0; i < toAddress.length; ++i) {
            addressTo[i] = new InternetAddress(toAddress[i]);
        }
        InternetAddress[] addressCC = new InternetAddress[ccAddress.length];   
        for (int i = 0; i < ccAddress.length; ++i) {
            addressCC[i] = new InternetAddress(ccAddress[i]);
        }
        InternetAddress[] addressBCC = new InternetAddress[bccAddress.length];
        for (int i = 0; i < bccAddress.length; ++i) {
            addressBCC[i] = new InternetAddress(bccAddress[i]);
        }                                                                     //setting address to,cc,bcc
     
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        msg.setRecipients(Message.RecipientType.CC, addressCC);
        msg.setRecipients(Message.RecipientType.BCC, addressBCC);
       
       
        msg.setSubject(subject);                                                 //setting subject
        messageBodyPart.setContent(message, "text/plain");    //setting body

        multipart.addBodyPart(messageBodyPart);         //adding body part to the multipart(msg)

     
        if (attach != null && attach.length > 0) {                            //attachmnt
            for (String filePath : attach) {

                MimeBodyPart attachPart = new MimeBodyPart();        //create second obj for bodypart to send attchmnt
           
                try {
                    attachPart.attachFile(filePath);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }

                multipart.addBodyPart(attachPart);            //adding body part to the multipart(attachmnt)
            }
        }

        msg.setContent(multipart);
        Transport.send(msg);                                             //sending mail
    }

}

No comments:

Post a Comment