Sunday 4 August 2013

Send Email in Soap UI using Groovy

Hi Guys,

Here is the code to send email in SoapUI using groovy.

Requirement: Java Mail Jar file location
http://www.java2s.com/Code/JarDownload/java/java-mail-1.4.4.jar.zip

// Note: Generally in SoapUI no need of java mail jar file but if require then can download from above link and save at ext directory.

Sending email "Gmail" SMPT server:

import com.sun.mail.smtp.SMTPTransport;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public static void Send(final String username, final String password, String recipientEmail, String ccEmail, String title, String message) throws AddressException, MessagingException {
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        // Get a Properties object
        Properties props = System.getProperties();
        props.setProperty("mail.smtps.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        props.setProperty("mail.smtps.auth", "true");

        /*
        If set to false, the QUIT command is sent and the connection is immediately closed. If set
        to true (the default), causes the transport to wait for the response to the QUIT command.

        ref :   http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/package-summary.html
                http://forum.java.sun.com/thread.jspa?threadID=5205249
                smtpsend.java - demo program from javamail
        */


        props.put("mail.smtps.quitwait", "false");

        Session session = Session.getInstance(props, null);

        // -- Create a new message --
        final MimeMessage msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username + "@gmail.com"));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientEmail, false));

        if (ccEmail.length() > 0) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccEmail, false));
        }

        msg.setSubject(title);
        msg.setText(message, "utf-8");
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport)session.getTransport("smtps");

        t.connect("smtp.gmail.com", username, password);
        t.sendMessage(msg, msg.getAllRecipients());     
        t.close();
    }

 log.info Send(username, password, recipientEmail, ccEmail, title, message);

58 comments:

  1. Hey, how can I use your Code in my Groovy Script - just pasting the code and fill the variables will bring me a syntax error :-/

    ReplyDelete
  2. Hi,

    1. Have you import all the libraries mentions in the code?
    2. Can you share the Syntax error you are getting as this is tested code on SoapUI 4.5.1 version.

    ReplyDelete
  3. I converted the code above into a java class (JAR File) and added the file into the /bin/ext-Folder.
    When I try importing the class into a groovy script I get an error:
    org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script4.groovy: 1: unable to resolve class JavaMailClass @ line 1, column 1. import JavaMailClass

    My script looks like:
    import JavaMailClass
    log.info JavaMailClass.Send("asd","asd","asd","asd","asd","asd")

    Any suggestions?

    ReplyDelete
  4. As per your comment it seems that Soapui does not able to compile your own created JavaMailClass Jar file that's mean there is issue with in JavaMailClass jar file which we need to resolve

    Suggestions:
    1. Check that JavaMailClass jar working properly or not and for that you can check it with in Eclipse.
    2. Instead of creating separate Java Class, direct create a function in SoapUi and use it in your project.
    3. If you are using SoapUi Pro version than create a function in groovy file then save it n Library and use it. :)

    ReplyDelete
  5. Sorry, I first copy and pasted it into a Groovy Script Step and it did not work (Syntax error). So I thought this might be working with a JavaClass etc. etc., but I tried it again, just by copy&paste to a Script Step and it worked :-/
    Nice script, nice work ;) Worked fine.
    Thanks a lot!

    ReplyDelete
  6. Great!!
    Your Welcome :)
    Happy Testing

    ReplyDelete
  7. where we need to pass email IDs?

    ReplyDelete
  8. Hi Shruthi,

    Above function is specific to gmail. So instead of Sender's emailId you need to enter its username only in first argument of function i.e. "username".

    For Example:
    If Gmail Id is : shruthitest@gmail.com then,
    in "username" Argument enter only above gmailId username only i.e. "shruthitest". It will automatically pick it as complete emailId.

    I hope it will help you, still have any question please revert.
    Happy Testing!!!

    ReplyDelete
  9. javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465; nested exception is: java.net.ConnectException: Connection timed out: connect error at line: 59

    Could you please help

    ReplyDelete
    Replies
    1. Generally it happen due to secure protocol.

      try the above code with change all the HTTP to HTTPS in above code and try again.

      Let me know if still it wont work.

      Regards,
      Saurabh Gupta

      Delete
    2. Hi Saurabh

      I'm getting the below error :

      Thu Feb 04 11:24:34 EST 2016:ERROR:javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
      nested exception is:
      java.net.ConnectException: Connection timed out: connect

      Can you help me what to change with HTTP, there is no where I see HTTP in the above code ?

      Delete
    3. try to add a new property:
      props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

      Or try to disable your firewall setting or antivirus as sometime they block to send the request.

      Please revert if that does not help.

      Regards,
      Saurabh Gupta

      Delete
    4. I couldn't disable my firewall but using my company's own smtp client which is allowed and working for me.

      Thank you for your prompt reply

      Delete
  10. This code is nor clear, where do we put argument for username, password...?

    ReplyDelete
    Replies
    1. Hi Kindle,

      If you are using the above code then you need to send the information at calling the function like:

      username "kindleowner"
      password = "password123"
      recipientEmail = "saurabhguptacse@gmail.com"
      ccEmail = "test@gmail.com"
      title = "Test Email"
      message = "Test message"

      log.info Send(username, password, recipientEmail, ccEmail, title, message);

      If using above code then you only need to provide above information.

      Note: Above code specific to gmail thats why you need to enter the FROM username instead of complete emailId. For example if gmail id is: kindleowner@gmail.com then enter "kindleowner" in username argument.

      Please let me know if still facing issue.

      Delete
    2. Hi Saurabh,

      I still have problems with the script. Let me brief you steps I have followed
      1. Created SOAP UI project - > Test Suite -> Test Case
      2. Added a test step (Groovy Script) in the Test Editor
      3. In the Groovy script Editor pasted the code above mentioned except (log.info Send(username, password, recipientEmail, ccEmail, title, message);

      My question is where to call the log.info Send(username, password, recipientEmail, ccEmail, title, message);

      Please correct me if I have gone wrong in any of the steps I have followed.

      Delete
    3. Hi Pallavi,

      Just tell me have you downloaded the required jar files and updated on desired location mentioned above.

      Second please share the error message you are getting

      Third Please share what values you are providing to me.

      Or if possible send me your complete groovy script on my personal email id: saurabhguptacse@gmail.com

      Regards,
      Saurabh Gupta

      Delete
    4. Hi Saurabh,

      Thanks for the quick reply. I had problems with firewall settings. Otherwise, the script works perfectly fine.

      Delete
  11. Hi Saurabh,

    The article gives the enough information for new comers like me on groovy.
    I tried the same script for sending the email through SOAPUI, however did not succeed.
    Steps performed:
    1. Created SOAP UI project - > Test Suite -> Test Case
    2. Added a test step (Groovy Script) in the Test Editor
    3. In the Groovy script Editor pasted the code above mentioned except (log.info Send(username, password, recipientEmail, ccEmail, title, message);

    I have copied the java email jars to the below path:
    C:\Program Files (x86)\SmartBear\SoapUI-5.0.0\bin\ext

    I am sending the SOAPUI project to your email: saurabhguptacse@gmail.com.
    Could you please check and help me in this regard.

    ReplyDelete
  12. Hi Ramakrishna, Can you share the exception you are getting while executing this function.

    ReplyDelete
  13. Hi Saurabh,

    I do not see any exception related to script but not able to receive any email. The test suite where the Groovy script resides did not process fully neither any exception. I have sent you the SOAPUI project, kindly have a check.

    ReplyDelete
  14. Hi Ramakrishna,

    I found 2 different things:
    1. On this line : msg.setFrom(new InternetAddress(username + "@gmail.com")); you use your name instead of variable userName.
    2. I did not see any calling statement for that function. Like: log.info Send("TestUserName", "TestPassword", "testrecipientemailid@gmail.com", "", "Test Title", "test message");

    In above line 1st parameter take the user name of gmail id from which you need to send email.
    2nd Parameter is password of username which given in 1st parameter
    3rd parameter is the email id where you wanna to send email
    4th Subject of email
    5th Body/content of email

    Try that and let me know if still not works for you

    ReplyDelete
  15. Hi Saurabh,

    Thanks for the timely help.
    I have modified as per your suggestions. Still I do not any exception or email. I am sending you the SOAP project again. Kindly have a look and do the needful.

    ReplyDelete
  16. Hi Saurabh,

    The script is working perfect now after putting the credentials properly. Please ignore my requests.
    Thank you very much for your time.

    ReplyDelete
  17. Hi Rama,

    Hi,

    Please find the updated project in separate mail.
    Before execution the steps follow below steps for gmail access:
    1. Login on Gmail.
    2. Open https://www.google.com/settings/security/lesssecureapps
    3. Chnage the Security to "Turn On".

    After that update the username and password in function calling and run the step.

    Please let me know if still not work as I tried and it worked perfectly.

    ReplyDelete
  18. Hi Saurabh,

    Your script is working perfectly :-).
    Thank you very much for your time. Great efforts.

    ReplyDelete
  19. Hi Saurabh,

    Can we execute this email SOAPUI groovy script through ANT?

    ReplyDelete
    Replies
    1. I hope so.. Ant is a build tool so create a function of it and execute it. Moreover I have always used Maven. So you need to google it out.

      Delete
  20. Hi Saurabh, i used the above code and used my gmail id as sender and my officeid as reciever but i am getting following exception "javax.mail.AuthenticationFailedException " i have given valid gmail credentials even then i am getting this error

    ReplyDelete
  21. Hi Avinash,

    Before execution the steps follow below steps for gmail access:
    1. Login on Gmail.
    2. Open https://www.google.com/settings/security/lesssecureapps
    3. Chnage the Security to "Turn On".

    After that update the username and password in function and run again.

    Please let me know if still it wont work.

    Regards,
    Saurabh Gupta

    ReplyDelete
  22. Hi Saurabh,

    I used the above code and it is working fine for sender as gmail address but not working for office id as sender as well as recipient.

    getting "javax.AuthnticationfailedException"

    ReplyDelete
    Replies
    1. For office id you need set different property values related to SMTP as per your office information. In above mention code its specific for gmail.
      If you are using above code then you need to use any working gmail id as sender.

      Delete
    2. Saurabh,

      where to update the SMTP details of my office id in above code.

      which code need to use for that.

      Delete
    3. Hi Saurabh,

      I have changed the gmail SMTP address to our office SMTP host address and port but it's showing "authenticationfailedexception"

      Delete
    4. Please tell me have you office mails partner is google? If yes then follow following steps:
      1. Login to your office mail with your UserName and Password which you are going to use as the sender.
      2. Then, open https://www.google.com/settings/security/lesssecureapps
      3. Change the Security to “Turn On”.

      If no then please change all SMTPS to SMTP and try again.

      Delete
    5. As you mentioned above, changed the security settings and getting below error

      "javax.mail.MessagingException: Exception reading response; nested exception is: javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection"

      Delete
    6. As per my understanding your official E-mail are on google mail only. So please use SMTPS as previously and change the security setting as mention in previous comment.

      Delete
  23. Hi Saurabh,

    Can we use the above email sending groovy script, once the Testrunner is complete and it will attach the test report to the email and send it to the recipients.

    Please let me know if you need further information

    ReplyDelete
    Replies
    1. Hello Saurabh,

      Could you please reply to the above question.

      Delete
    2. Option-1: Put it in TearDown script to attach report and send it on mail.

      Option-2. Create another testrunner batch file which attached the 1st script report in mail and send to recipient.
      To Achieve that you can follow following steps:
      1. In the main test suite add a tear down script which store the path of result file in some external file say notepad at C: drive.
      2. After that execute the second script to send email, in that fetch the report path from that external file and attach it with mail and send it.

      Option-3: Create your own report and then use option 1 for emailing. Why refering own customized report because:
      1. You can add more information in report as per your requirement
      2. It will be execute in same script. No need to separate script.
      3. I have done in this way and it was very effective for me.

      I hope it will help you to achieve your target.

      Delete
  24. Hi Saurabh,

    How can I pass a variable in this mail

    ReplyDelete
    Replies
    1. What kind of variable you need to send??
      Example of calling above function is:
      log.info Send("sampleUser", samplepassword, abc@gmail.com, "", "Subject: Test mail", "Sample Message body which need to send in mail");

      Delete
  25. Hi Saurabh,

    My company gave me company mail id for this script but that does not have a password like donotreply how can I add this

    ReplyDelete
    Replies
    1. This function is for Gmail only. For usage of company related emailId: you need to change the code little bit like SMTP as per your company email.
      If you need any help mail me on saurabhguptacse@gmail.com

      Delete
    2. Ok!
      So You need to change few information in your code:
      1st:
      // Get a Properties object
      Properties props = System.getProperties();
      props.setProperty("mail.smtps.host", "smtp.gmail.com");
      props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
      props.setProperty("mail.smtp.socketFactory.fallback", "false");
      props.setProperty("mail.smtp.port", "465");
      props.setProperty("mail.smtp.socketFactory.port", "465");
      props.setProperty("mail.smtps.auth", "true");
      Change this properties as per your company email information.
      2nd: // -- Set the FROM and TO fields --
      msg.setFrom(new InternetAddress(username + "@gmail.com"));
      Change '@gmail.com' part as per your company email id.
      3rd: t.connect("smtp.gmail.com", username, password);
      Change "smtp.gmail.com" to your organization smtp information and in password give it blank value like "".

      I hope it will help you.

      Regards,
      Saurabh Gupta

      Delete
  26. In mail I want to write like this
    line 1
    Line 2
    .
    .
    .
    how can I do like this

    ReplyDelete
    Replies
    1. Hi..
      Now it worked for you?
      And for multiple line in SoapUI create a String like
      def a = "Line 1" + System.getProperty("line.separator") + "Line 2" + System.getProperty("line.separator") + "Line 3";

      It will print like:
      Line1
      Line2
      Line3

      Revert me in case of any changes and now on you can follow me on testarenablog.wordpress.com.
      I will be more active over there

      Delete
    2. How we can generate HTML report with ths

      Delete
    3. First Question: Are you using SoapUI Open Source or SoapUI pro.
      If pro then it self provide HTML report.
      If not then you can generate yours using groovy code. It will be very lengthy for me to tell you how you can create HTML report

      Delete
    4. Do you have sample script for this

      Delete
    5. Sorry need to create it. And for that it will take lot of time.

      Delete
    6. ${#TestSuite#AccountNo}
      if I have different test suits(suppose suit1 & suit 2) in one project then how can I call the variable

      Delete
    7. Hi,

      There is no direct way to fetch one testuite property from another testsuite. Another way to that:
      1. Create 2 TestSuite named: a. TestSuite1 and b. TestSuite2
      2. Create a custom property in TestSuite1 with name: 'testproperty'.
      3. Now Add one test case in TestSuite2 and add one groovy step in test case.
      4. Use the following code from test case of TestSuite2:
      def project = testRunner.testCase.testSuite.project
      def testSuite = project.getTestSuiteByName('TestSuite1')
      log.info testSuite.getPropertyValue('testproperty')

      In this way you can store those value in TestSuite2 and use it.

      follow this for properties access using groovy:
      https://testarenablog.wordpress.com/2016/08/13/soapui-properties/

      Delete
  27. Hi Saurabh,

    I have copied the same script and I am getting the below error

    Error :

    javax.mail.AuthenticationFailedException



    ReplyDelete
    Replies
    1. Follow the below step and try again:
      1. Login to gmail with your UserName and Password which you are going to use as the sender.
      2. Then, open https://www.google.com/settings/security/lesssecureapps
      3. Change the Security to “Turn On”.
      4. After that again run the code.

      I hope it will help you.

      Delete