Saturday 16 August 2014

Using Groovy to send Emails

Background

In this post we will see how can we write a groovy script to send emails. I am going to use javax.mail and javax.activation for this. To setup groovy environment you can refer to one of my earlier posts - 




Code

/**
 * @author athakur
 *
 */

@Grapes([
    @Grab(group='javax.mail', module='mail', version='1.4.7'),
    @Grab(group='javax.activation', module='activation', version='1.1.1'),
    @GrabConfig(systemClassLoader=true)
])

import javax.mail.internet.*;
import javax.mail.*
import javax.activation.*

class EmailSender {
    
    public static void main(def args){
        //to test the script
        EmailSender emailSender = new EmailSender();
        emailSender.sendmail();
    }
    
    def static message = "Test Message";
    def static subject = "Test Message Subject";
    def static toAddress = "test1@opensourceforgeeks.com";
    def static fromAddress = "test2@opensourceforgeeks.com";
    def static host = "test.email.opensourceforgeeks.com";
    def static port = "25";
    
    public EmailSender() {
        
    }

    def static sendmail() {
        sendmail(message, subject, toAddress, fromAddress, host, port);
    }
    
    def static sendmail(String message ,String subject, String toAddress, String fromAddress, String host, String port){
        Properties mprops = new Properties();
        mprops.setProperty("mail.transport.protocol","smtp");
        mprops.setProperty("mail.host",host);
        mprops.setProperty("mail.smtp.port",port);

        Session lSession = Session.getDefaultInstance(mprops,null);
        MimeMessage msg = new MimeMessage(lSession);

        StringTokenizer tok = new StringTokenizer(toAddress,";");
        ArrayList emailTos = new ArrayList();
        while(tok.hasMoreElements()){
            emailTos.add(new InternetAddress(tok.nextElement().toString()));
        }
        InternetAddress[] to = new InternetAddress[emailTos.size()];
        to = (InternetAddress[]) emailTos.toArray(to);
        msg.setRecipients(MimeMessage.RecipientType.TO,to);
        msg.setFrom(new InternetAddress(fromAddress));
        msg.setSubject(subject);
        msg.setText(message)

        Transport transporter = lSession.getTransport("smtp");
        transporter.connect();
        transporter.send(msg);
        
        println("Message sent");
    }
}



 Then you can simply run it with groovy EmailSender.groovy.

Note :  you can import all packages you need using the grab syntax mentioned in the top of the script.
 To know the group, module and version you can search the Maven repository.  In the link there is a separate tab for grape like there is for ivy, maven or gradle. So you can directly pick up the syntax from there. For example if you search for javax.activation you can see the following syntax under grape tab - 


@Grapes(

        @Grab(group='javax.mail', module='mailapi', version='1.4.3')

)



t> UA-39527780-1 back to top