sahi

how to send an email with attachment through sahi UI


I am trying to send am email with attachment through SAHI UI. But I am unable to do so. Can someone help me. The code that I am using for sending an email is as follows:

function sendEmailWithAttachment($emailUsername, $emailPassword, $toEmail, $emailSubject, $emailBody) 
{
  var $host = "smtp.gmail.com";
  var $port = 465;
  var $isSSL = true; // set to true if you use SSL
  var $mailer = new Packages.net.sf.sahi.ant.Mailer($host, $port, $emailUsername, $emailPassword, $isSSL);
  var $from = $emailUsername;
  var $to = $toEmail;
  $mailer.addAttachment("3_PO#POS-POS-008-003358 DELL.pdf", "../../../../../lib/VSAAutomation.Common/3_PO#POS-POS-008-003358 DELL.pdf");
  $mailer.send($from, $to, $emailSubject, $emailBody);
}

And I am calling the function in this manner:

sendEmailWithAttachment($notifyEmailId, $notifyEmailPassword, $emailReaderId, "automateticket"+$randomNum, "automated ticket from Sahi");

Also just to let you know that I have put mail.jar, activation.jar and ant-sahi.jar files at their correct places


Solution

  • Please use these functions to send emails with attachments. You can provide the attachment as commented in the code below.

    function sendEmailWithProps($emailSubject, $emailBody) {
      var $props = loadProperties(_resolvePath("../config/email.properties"), false);
      var $mailer = new Packages.net.sf.sahi.ant.Mailer($props);
      var $subjectPrefix = $props.getProperty("mail.subject.prefix");
      if($subjectPrefix !== null){
    $emailSubject = $subjectPrefix + $emailSubject;
      }
    $mailer.addBody($emailBody);
    $mailer.addSubject($emailSubject);
    
    //Provide attachment details here
    $mailer.addAttachment("attached", "c:/abc.txt");
    $mailer.send();
    }
    
    function loadProperties($path, $isXML) {
      var $props = new java.util.Properties();
      try {
        var $inStream = new java.io.FileInputStream($path);
        if ($isXML) {
          $props.loadFromXML($inStream);
        } else {
          $props.load($inStream);
        }
        $inStream.close();
      } catch (e) {
                _log(e);
      }
      return $props;
    }
    sendEmailWithProps("Mail from Sahi", "All izz well");
    

    Note that you need to have a fully configured email.properties file in userdata/config folder. This is a bit tricky as you need to use the properties file for sending email with attachments.