The Kahimyang Project Logo
Primo's Code Blog
Howtos tips and tricks
The Kahimyang Project

A Java class for sending multipart Email messages through your Gmail account

Here is a Java class for sending multipart (text and file attachments) email messages through your Gmail account. This class is suitable for use in your JSF backing bean.

JavaMail library must be in your project. Get JavaMail here.



package your-package;

import javax.mail.PasswordAuthentication;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class Email {
    
    public void send(String recipeintEmail, 
            String subject, 
            String messageText, 
            String []attachments) 
            throws MessagingException, AddressException {
        /*
           It is a good practice to put this in a java.util.Properties 
           file and encrypt password. Scroll down 
           to comments below to see 
           how to use java.util.Properties in JSF context. 
        */
        String senderEmail = "your-gmail-account@gmail.com";
        String senderMailPassword = "sender-account-password";
        String gmail = "smtp.gmail.com";
        
        Properties props = System.getProperties();

        props.put("mail.smtp.user", senderEmail);
        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.debug", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", 
              "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");

        // Required to avoid security exception.
        MyAuthenticator authentication = 
              new MyAuthenticator(senderEmail,senderMailPassword);
        Session session = 
              Session.getDefaultInstance(props,authentication);
        session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        
        BodyPart messageBodyPart = new MimeBodyPart();      
        messageBodyPart.setText(messageText);
        
        // Add message text
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        
        // Attachments should reside in your server.
        // Example "c:\file.txt" or "/home/user/photo.jpg"

        for (int i=0; i < attachments.length; i++) {        
            messageBodyPart = new MimeBodyPart();       
            DataSource source = new FileDataSource(attachments[i]);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachments [i]);          
            multipart.addBodyPart(messageBodyPart) ;  
        }
        
   
           
        message.setContent(multipart);                
        message.setSubject(subject);
        message.setFrom(new InternetAddress(senderEmail));
        message.addRecipient(Message.RecipientType.TO,
            new InternetAddress(recipeintEmail));

        Transport transport = session.getTransport("smtps");
        transport.connect(gmail,465, senderEmail, senderMailPassword);
        transport.sendMessage(message, message.getAllRecipients());
        
        transport.close();
        
    }
    
    private class MyAuthenticator extends javax.mail.Authenticator {
        String User;
        String Password;
        public MyAuthenticator (String user, String password) {
            User = user;
            Password = password;
        }
        
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return new javax.mail.PasswordAuthentication(User, Password);
        }
    }
    
}
  
  
  

Good luck.

RSS Logo



Comment icon   Comments (Newest first)

Recent posts in Java/JSF category
Blue dot icon Using Rhinoslider with image and youtube content in JSF pages
Blue dot icon A dynamic standard sitemap.xml with Google image extension implemented as a Java Servlet
Blue dot icon Creating a Facebook-like panel with slim scrollbars and infinite scrolling in PrimeFaces
Blue dot icon Generating XML RSS 2 feeds with JDOM 2 with a servlet
Blue dot icon Building a page with infinite scroll in PrimeFaces using Waypoints jQuery plugin
Blue dot icon Implementing a collapsible ui:repeat rows in JSF
Blue dot icon Validating an email address in PrimeFaces p:inputText field with p:ajax





Most popular articles
Blue dot icon Using Expect script to automate SSH logins and do routine tasks accross multiple hosts   (15297)
Blue dot icon How to setup Tomcat 7 as your primary webserver on Debian Squeeze    (14056)
Blue dot icon How to setup FLV streaming with crtmpserver C++ RTMP server   (9775)
Blue dot icon A Java class for sending multipart Email messages through your Gmail account    (6969)
Blue dot icon How to use Google Translate's Text to Speech (TTS) services in your web page using Servlet   (5645)
Blue dot icon Speed up Primefaces page load with p:remoteCommand partial update   (5417)
Blue dot icon Building a mobile website with JSF 2 core and JQuery Mobile 1.0   (5310)
Blue dot icon Google Map-Adding markers, info window, circle, small control, and events in Javascript    (5210)