Saturday, September 12, 2009

Sending email using groovy

My first groovy task was to write a simple test harness that would send an email. This was not the easiest thing in the world I have to say. I guess the groovy folks didn't add anything to groovy to make sending email easier than it is in straight java. There is a grail mail plugin that looks good, but I didn't want to add the dependency just to send an email and wasn't sure it would work just with groovy.

The first mistake I made was to try and figure out how to create a "main" method. I spent about half an hour before figuring out I don't need one. I now make sure to chant "scripting language" three times before I do anything with groovy. This has helped a lot.

As an aside, this scripting language plus the seemless integration into java is a wonderful reason to use groovy for unit tests. Even if you don't buy into anything else about groovy it would be great for rapid creation of JUnit tests.

So here is my very first groovy script (I almost said app, "scripting language...scripting language"). I am sure I have done all kinds of things that are not quite right, but it sends me an email which for now is good enough. If for some reason you would like to use it feel free it is licensed under the MIT license. Just copy and paste it into a new file, make sure you have mail.jar (from java-mail) and activation.jar in your classpath and groovy it.


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


message = "test groovy mail"
subject = "groovy sent this"
toAddress = "to@example.com"
fromAddress = "from@example.com"
host = "localhost"
port = "25"

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);


//tokenize out the recipients in case they came in as a list
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);
InternetAddress fromAddr = new InternetAddress(fromAddress);
msg.setFrom(fromAddr);
msg.setFrom(new InternetAddress(fromAddress));
msg.setSubject(subject);
msg.setText(message)

Transport transporter = lSession.getTransport("smtp");
transporter.connect();
transporter.send(msg);

26 comments:

  1. Great stuff, well done with this.

    ReplyDelete
  2. just use the antBuilder.
    def ant = new AntBuilder()
    ant.mail(....)

    done and done.

    ReplyDelete
  3. Yes this does work but you also may need to include ant-javamail.jar in your classpath or groovy lib dir (I did using groovy 1.6.4) and it doesn't work in embedded environments that don't include ant libs (using the groovy-all-XX.jar).

    The use of the AntBuilder to send mail seems to be a pretty popular solution. After using groovy some more I have used the AntBuilder in simple scripts that I run for my own automation running in a local environment, but for anything else I put a closure around the above and use that. In the end a lot less head aches.

    ReplyDelete
  4. This was most helpful, I used it as a launchpad for creating a notification task in Gradle (may move it into a real plugin)

    ReplyDelete
  5. Hi,

    I'm using the above mentioned code with soapUI tool to trigger an Email once the test is completed. I replaced the host and port as per the network config at my company and tried to execute the script and found that it was throwing an exception. When i verified the log file i found that the script is still trying to connect to localhost:25. Can you please help in rectifying this issue?

    Thanks and Regards,
    Sandeep

    ReplyDelete
    Replies
    1. Sorry not sure what it could be. I just tried this again changing the host and port to see if I had some error and it worked for me.

      Delete
  6. Hey Brook,
    SMTP service is not running in my machine and for QTP scripts, i use smtp.gmail.com, is there any way I can convert this script to use smtp.gmail.com, using my gmail email address and password.

    ReplyDelete
  7. Mái tóc đẹp luôn là niềm ao ước của nhiều chị em. luôn tìm cách để cho mình có được mái tóc đẹp như ý. Chính vì thế cho nên việc làm và tìm các kiểu tết tóc đẹp trong mỗi thời gian luôn được các chị em quan tâm đến. Việc làm và dưỡng tóc hiện nay nhiều phương pháp khác nhau như thẩm my, dầu gội, sử dụng tinh dầu thiên nhiên. Chính vì thế các dịch vụ spa, dưỡng tóc hình thành nhằm đáp ứng nhu cầu ấy và tốt hơn hẳng ngày nay việc sử dụng tinh dầu thiên nhiên làm đẹp và dưỡng tóc ngày càng phổ biến cụ thể là ủ tóc dầu dừa sẽ cho bạn mái tóc khỏe mạnh nhanh chóng trong 1 tuần sử dụng. Không quá khó khăn cũng như công đoạn và cách thực hiện nhanh chóng có thể giúp bạn có mái tóc như ý. Và dầu dừa cũng là một trong nguyên liệu được áp dụng rộng rãi trong việc sử dụng cách làm tóc nhanh dài trong 1 tuần hiệu quả an toàn cho các chị em. Và sau khi bạn sở hữu được mái tóc dài chắc khỏe đen bóng thì việc còn lại bạn nên chọn lựa cho mình những kiểu tóc đẹp phù hợp với khuôn mặt và vóc dáng của mình và một trong những kiểu tóc luôn được các chị em phụ nữ chọn lựa cho mái tóc xoăn. Vậy các làm mái tóc xoăn như thế nào cúng chúng tôi tìm hiểu cách là̀m tóc xoăn tự nhiên đơn giản. Hy vọng vói thông tin chia sẻ trên bạn có thể chọn lựa cho mình cách dưỡng và làm đẹp tóc hiệu quả ngay tại nhà của mình nhé!

    ReplyDelete

  8. The primary thing they did was evacuate all expenses connected with the arrangement and make it FREE! This was cheered by us and we couldn't sit tight for more individuals to begin getting a charge out of what we believe is one of the best examination arrangement accessible, regardless of what the expense.https://800support.net/yahoo-support/how-to-group-and-delete-emails-by-conversations-in-yahoo/

    ReplyDelete
  9. Solve all complicated issues using help number of Gmail.Help Number of Gmail

    ReplyDelete
  10. A very Impressive and detailed post. Thanks for sharing such a wonderful and important information.
    For more info how to fix yahoo problems visit us @ Visit here

    ReplyDelete