Monday 10 June 2013

Sending Email with java

Hi,
I had to send an email using java, I wrote a java class that helps you shooting emails.
I am sharing the source code so that it can be used by others too..
It doesn't support email attachments as it was not the requirement in my case but it can be done too..
Thanks



Things to download
1) java mail API

I used: mailapi.jar



2) My written java Class

package com.breeze.utils;

import java.security.GeneralSecurityException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.breeze.property.AppProperties;
import com.sun.mail.util.MailSSLSocketFactory;

public abstract class EmailAgent {

    public static boolean sendTextOnlyEmail(String to, String from, String subject,String message){
       
       
        final Properties properties=AppProperties.getSystemProperties();
       
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", properties.getProperty("mail.smtp.host")); // for gmail use smtp.gmail.com
        props.put("mail.smtp.auth", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", properties.getProperty("mail.smtp.port"));
        props.put("mail.smtp.socketFactory.port", properties.getProperty("mail.smtp.socketFactory.port"));
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "true");

        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
        } catch (GeneralSecurityException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.socketFactory", sf);
       
        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {

            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(properties.getProperty("mail.smtp.username"), properties.getProperty("mail.smtp.password"));
            }
        });

        mailSession.setDebug(true); // Enable the debug mode

        Message msg = new MimeMessage( mailSession );

        //--[ Set the FROM, TO, DATE and SUBJECT fields
        try {
            msg.setFrom( new InternetAddress( from ) );
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            msg.setRecipients( Message.RecipientType.TO,InternetAddress.parse(to) );
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //msg.setSentDate(new Date());
        try {
            msg.setSubject( subject );
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //--[ Create the body of the mail
        try {
            msg.setText(message );
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //--[ Ask the Transport class to send our mail message
        try {
            Transport.send( msg );
            return true;
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }   
    }

        public static void main(String[] args){
            EmailAgent.sendTextOnlyEmail("sandeelo.danyal@gmail.com","youremail@domain.com","Need to talk" ,"Hi, This is a testing message. ");
        }
   
}


Use this utility to send text emails.
You can use database to store templates, depends on your needs and requirements. This is a simple code that lets you know how to use mail API.

I have taken a number of values from PROPERTY file to keep the things dynamic.

#----email properties
mail.smtp.host=smtp.company.biz
mail.smtp.port=25
mail.smtp.socketFactory.port=25
mail.smtp.username=username@ursmtp.com
mail.smtp.password=yourPassword
to=to@email.com
from=from@email.com
subject=your subject
emailSuccessMessage=Email has been sent // I have kept this message dynamic, using it on jsp when the //email is sent successully




No comments:

Post a Comment