Saturday, 16 August 2014

Using Groovy to send Emails


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 - 


 * @author athakur

    @Grab(group='javax.mail', module='mail', version='1.4.7'),
    @Grab(group='javax.activation', module='activation', version='1.1.1'),

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();
    def static message = "Test Message";
    def static subject = "Test Message Subject";
    def static toAddress = "";
    def static fromAddress = "";
    def static host = "";
    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();

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

        StringTokenizer tok = new StringTokenizer(toAddress,";");
        ArrayList emailTos = new ArrayList();
            emailTos.add(new InternetAddress(tok.nextElement().toString()));
        InternetAddress[] to = new InternetAddress[emailTos.size()];
        to = (InternetAddress[]) emailTos.toArray(to);
        msg.setFrom(new InternetAddress(fromAddress));

        Transport transporter = lSession.getTransport("smtp");
        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 - 


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


t> UA-39527780-1 back to top