public static void main(String[] args) {
    try {

      String htmlEmailTemplate = ".... <img src=\"http://www.apache.org/images/feather.gif\"> ....";
      URL url = new URL("http://www.apache.org");
      ImageHtmlEmail email = new ImageHtmlEmail();
      email.setDataSourceResolver(new DataSourceUrlResolver(url));
      email.setHostName("HERA.i-heart.co.kr");
      email.setSmtpPort(587);
      email.setAuthenticator(new DefaultAuthenticator("*****@*****.**", "tjddlsdpdltm6*"));
      email.setFrom("*****@*****.**");
      email.setSubject("TestMail");
      email.setMsg("This is a test mail ... :-)"); // 여기서는 이놈이 안보일거임.
      email.addTo("*****@*****.**");
      email.setDebug(true);

      // HTML Message 세팅
      email.setHtmlMsg(htmlEmailTemplate);
      // Client가 HTML Message를 지원하지 않으면 TextMsg를 띄워준다.
      email.setTextMsg("Your email client does not support HTML messages");
      email.send();

    } catch (EmailException e) {
      e.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 2
0
 public void handle(Message msg, Session sess) throws IOException {
   Email email = Json.fromJson(Email.class, msg.getBodyString());
   try {
     email.send();
   } catch (EmailException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 3
0
 public void sendEmailConfirmacao(Empresa empresa) {
   String link =
       "http://www.extratosfacil.com.br/confirmar.html?sb{bpTpdjbm="
           + this.crip(empresa.getRazaoSocial());
   String mensagem = "<p>Cadastro realizado com sucesso. Clique no link para confirmar: </p>";
   String assunto = "Cadastro Extratos F�cil";
   try {
     Email.sendEmail(empresa.getEmail(), empresa.getNomeFantasia(), assunto, mensagem, link);
   } catch (EmailException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 4
0
  //	public static void sendFileMail() throws MessagingException {
  //	        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
  //
  //	        // 设定mail server
  //	        senderImpl.setHost("smtp.sina.com.cn");
  //	        senderImpl.setUsername("*****@*****.**");
  //	        senderImpl.setPassword("kimi3213.1415926");
  //	        // 建立HTML邮件消息
  //	        MimeMessage mailMessage = senderImpl.createMimeMessage();
  //	        // true表示开始附件模式
  //	        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");
  //
  //	        // 设置收件人,寄件人
  //	        messageHelper.setTo("*****@*****.**");
  //	        messageHelper.setFrom("*****@*****.**");
  //	        messageHelper.setSubject("测试邮件!");
  //	        // true 表示启动HTML格式的邮件
  //	        messageHelper.setText("<html><head></head><body><h1>你好:附件!!</h1></body></html>", true);
  //
  //
  //	        FileSystemResource file = new FileSystemResource(new File("d:/log.txt"));
  //
  //
  //	        try {
  //	            //附件名有中文可能出现乱码
  //	            messageHelper.addAttachment(MimeUtility.encodeWord("log.txt"), file);
  //	        } catch (UnsupportedEncodingException e) {
  //	            e.printStackTrace();
  //	            throw new MessagingException();
  //	        }
  //	        // 发送邮件
  //	        senderImpl.send(mailMessage);
  //	        System.out.println("邮件发送成功.....");
  //
  //	    }
  public static void sendMutiMessage() {

    MultiPartEmail email = new MultiPartEmail();

    String[] multiPaths = new String[] {"d:/output.xls"};

    List<EmailAttachment> list = new ArrayList<EmailAttachment>();
    for (int j = 0; j < multiPaths.length; j++) {
      EmailAttachment attachment = new EmailAttachment();
      // 判断当前这个文件路径是否在本地  如果是:setPath  否则  setURL;
      if (multiPaths[j].indexOf("http") == -1) {
        attachment.setPath(multiPaths[j]);
      } else {
        try {
          attachment.setURL(new URL(multiPaths[j]));
        } catch (MalformedURLException e) {
          e.printStackTrace();
        }
      }
      attachment.setDisposition(EmailAttachment.ATTACHMENT);
      attachment.setDescription("Picture of John");
      list.add(attachment);
    }

    try {
      // 这里是发送服务器的名字:
      email.setHostName("smtp.sina.com.cn");
      // 编码集的设置
      email.setCharset("utf-8");
      // 收件人的邮箱
      email.addTo("*****@*****.**");
      // 发送人的邮箱
      email.setFrom("*****@*****.**");
      // 如果需要认证信息的话,设置认证:用户名-密码。分别为发件人在邮件服务器上的注册名称和密码
      email.setAuthentication("*****@*****.**", "kimi3213.1415926");
      email.setSubject("设备监控数据");
      // 要发送的信息
      email.setMsg("详情请见附件");

      for (int a = 0; a < list.size(); a++) // 添加多个附件
      {
        email.attach(list.get(a));
      }
      // 发送
      email.send();
    } catch (EmailException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 5
0
 /**
  * @param username 用户名
  * @param ip 用户登录时的Ip
  * @param time 用户登录的时间
  */
 public void sendEmail(String username, String ip, String time) {
   SimpleEmail simpleEmail = new SimpleEmail();
   simpleEmail.setAuthentication("*****@*****.**", "Q2889144");
   simpleEmail.setHostName("smtp.126.com");
   simpleEmail.setSmtpPort(25);
   simpleEmail.setCharset("utf-8");
   try {
     simpleEmail.setFrom("*****@*****.**");
     simpleEmail.addTo("*****@*****.**");
     simpleEmail.setMsg(time + ",用户:" + username + "在" + ip + "登录");
     simpleEmail.setSubject("开会");
     simpleEmail.send();
   } catch (EmailException e) {
     e.printStackTrace();
   }
 }
 public void sendEmail() {
   try {
     List<Emails> emails = emailsDao.getEmailsByStatus('N');
     if (!ITeachUtility.isEmptyList(emails)) {
       for (Emails emailToSend : emails) {
         try {
           HtmlEmail email = new HtmlEmail();
           email.setHostName(ITeachUtility.getPropValue("hostName", true));
           email.setSmtpPort(Integer.parseInt(ITeachUtility.getPropValue("portNumber", true)));
           email.setAuthenticator(
               new DefaultAuthenticator(
                   ITeachUtility.getPropValue("userName", true),
                   ITeachUtility.getPropValue("password", true)));
           email.addTo(emailToSend.getEmailTo());
           email.setFrom(emailToSend.getEmailFrom(), emailToSend.getEmailFromName());
           email.setSubject(emailToSend.getEmailSub());
           String emailContent = emailToSend.getEmailBody();
           /*
            * if(StringUtils.isNotBlank(emailToSend.
            * getEmailAttachments ())){ Set<String>
            * attachments=ITeachUtility.getStringAsSet(emailToSend.
            * getEmailAttachments(), ","); }
            */
           // set the html message
           email.setHtmlMsg("<html>" + emailContent + "</html>");
           email.send();
           emailToSend.setSendAttempt(
               emailToSend.getSendAttempt() == null ? 1 : (emailToSend.getSendAttempt() + 1));
           emailToSend.setEmailStatus('S');
           emailToSend.setSentOn(Calendar.getInstance().getTime());
           System.out.println("sent email to " + emailToSend.getEmailTo());
         } catch (EmailException e) {
           // if any exception then updating the attempt.
           emailToSend.setSendAttempt(
               emailToSend.getSendAttempt() == null ? 1 : (emailToSend.getSendAttempt() + 1));
           e.printStackTrace();
         }
         emailsDao.updateEmails(emailToSend);
       }
     } else {
       System.out.println("No email to send.");
     }
   } catch (ITeachException ex) {
     ex.printStackTrace();
   }
 }
Ejemplo n.º 7
0
 public static void sendEmail(String feedbackTo, String subject, String message) {
   SimpleEmail email = new SimpleEmail();
   try {
     email.setHostName(
         ApplicationConfig.getInstance()
             .getProperty(Constants.CONFIG_PROPERTIES.FEEDBACK_EMAIL_HOST));
     email.addTo(feedbackTo);
     email.setFrom(
         ApplicationConfig.getInstance().getProperty(Constants.CONFIG_PROPERTIES.FEEDBACK_FROM));
     email.setSubject(subject);
     email.setMsg(message);
     email.send();
   } catch (EmailException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
Ejemplo n.º 8
0
 public void sendEmailPlaca(String placaErrada) {
   String destinatario = "*****@*****.**";
   String nomeDestinatario = "Extratos Facil";
   String assunto = "Placa Incorreta";
   String mensagem =
       "A placa "
           + placaErrada
           + " Esta cadastrada para empresa "
           + Sessao.getEmpresaSessao().getNomeFantasia()
           + " incorretamente, favor excluir do sistema.";
   String link = "extratosfacil.com.br/admin";
   try {
     Email.sendEmail(destinatario, nomeDestinatario, assunto, mensagem, link);
     Mensagem.send(Mensagem.EMAIL_ENVIADO, Mensagem.INFO);
   } catch (EmailException e) {
     Mensagem.send("Ocorreu um erro, por favor tente mais tarde!", Mensagem.ERROR);
     e.printStackTrace();
   }
 }
  private void enviaEmails(List<String> emails, String msg) {
    logger.entering(new Object[0]);

    if ((emails != null) && (!emails.isEmpty())) {
      for (String email : emails) {
        try {
          MessageUtil.enviaEmail(
              email,
              MessagesUtil.getMessage("MessageResources", "ass.alertas.atrasados"),
              msg,
              null);
        } catch (EmailException e) {
          logger.exception(e.getMessage(), e);
        }
      }
    }

    logger.exiting(new Object[0]);
  }
Ejemplo n.º 10
0
  public void sendSmtpTestMail(
      String smtpFromMail,
      String smtpHost,
      Integer smtpPort,
      String smtpUsername,
      String smtpPassword,
      String toMail) {
    SystemConfig systemConfig = SystemConfigUtil.getSystemConfig();
    MailConfig mailConfig = TemplateConfigUtil.getMailConfig(MailConfig.SMTP_TEST);
    String subject = mailConfig.getSubject();
    String templateFilePath = mailConfig.getTemplateFilePath();
    try {
      email = new HtmlEmail();
      email.setHostName(systemConfig.getSmtpHost());
      email.setSmtpPort(systemConfig.getSmtpPort());
      email.setAuthenticator(
          new DefaultAuthenticator(systemConfig.getSmtpUsername(), systemConfig.getSmtpPassword()));
      email.setSSLOnConnect(true);

      WebAppResourceLoader resourceLoader = new WebAppResourceLoader();
      Configuration cfg = Configuration.defaultConfiguration();
      GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
      Template template = gt.getTemplate(templateFilePath);
      template.binding("systemConfig", systemConfig);
      String text = template.render();

      email.setFrom(
          MimeUtility.encodeWord(systemConfig.getShopName())
              + " <"
              + systemConfig.getSmtpFromMail()
              + ">");
      email.setSubject(subject);
      email.setMsg(text);
      email.addTo(toMail);
      email.send();

    } catch (EmailException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 11
0
 public static void sendPromocao(Cotacao cotacao) {
   HtmlEmail email = new HtmlEmail();
   try {
     email.setHostName("mail.gentec.inf.br");
     email.setSmtpPort(587);
     email.setAuthentication("*****@*****.**", "123456");
     email.addTo("*****@*****.**");
     email.setFrom("*****@*****.**", "Pedido de Cota\347\343o");
     email.setCharset("ISO-8859-1");
     email.setSubject("Gentec IT");
     email.setHtmlMsg(
         (new StringBuilder("<html><body><h1> Empresa: "))
             .append(cotacao.getNomeEmpresa())
             .append("</h1>")
             .append("<br/>")
             .append("<div>")
             .append("Nome de Cliente: ")
             .append(cotacao.getNomeCliente())
             .append("<br/>")
             .append("CNPJ: ")
             .append(cotacao.getNumeroCnpj())
             .append("<br/>")
             .append("Telefone: ")
             .append(cotacao.getNumeroTelefone())
             .append("<br/>")
             .append("E-mail: ")
             .append(cotacao.getEmail())
             .append("<br/>")
             .append("Observa\347\365es: ")
             .append(cotacao.getObservacoes())
             .append("<br/>")
             .append("</div>")
             .append("</body>")
             .append("</html>")
             .toString());
     email.setTextMsg("Seu servidor de e-mail n\343o suporta mensagem HTML");
     email.send();
   } catch (EmailException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 12
0
  public static Result send() {

    final Form<Mail> categoryForm = play.data.Form.form(Mail.class).bindFromRequest();
    Map<String, Object> data = new HashMap<String, Object>();
    final Mail category = categoryForm.get();
    play.Logger.info(category.toString());
    play.Logger.info(category.dests.get(0));

    Mailing serviceMail = new Mailing();

    try {
      serviceMail.sendMailToAll(
          category.dests, category.msg, category.obj, category.filePath, category.fileName);
      data.put("status", Boolean.TRUE);
    } catch (EmailException e) {
      data.put("status", Boolean.FALSE);
      e.printStackTrace();
    }

    return ok(toJson(data));
  }
Ejemplo n.º 13
0
  public static Result sendMail() {
    Mailer email = new Mailer(play.Play.application());

    Map<String, String[]> formData = request().body().asFormUrlEncoded();
    email.addFrom(utils.HttpUtil.getFirstValueFromQuery(formData, "from"));
    email.setSubject(utils.HttpUtil.getFirstValueFromQuery(formData, "subject"));
    email.addRecipient(utils.HttpUtil.getFirstValueFromQuery(formData, "to"));

    String errorMessage = null;
    boolean sended = false;
    try {
      email.send(utils.HttpUtil.getFirstValueFromQuery(formData, "body"));
      sended = true;
    } catch (EmailException e) {
      errorMessage = e.toString();
      if (e.getCause() != null) {
        errorMessage += "<br/>Caused by: " + e.getCause();
      }
    }

    return writeMail(errorMessage, sended);
  }
Ejemplo n.º 14
0
  public boolean sendMail(
      String subject, String templateFilePath, Map<String, Object> data, String toMail) {
    boolean isSend = false;
    try {
      SystemConfig systemConfig = SystemConfigUtil.getSystemConfig();

      email = new HtmlEmail();
      email.setHostName(systemConfig.getSmtpHost());
      email.setSmtpPort(systemConfig.getSmtpPort());
      email.setAuthenticator(
          new DefaultAuthenticator(systemConfig.getSmtpUsername(), systemConfig.getSmtpPassword()));
      email.setSSLOnConnect(true);

      WebAppResourceLoader resourceLoader = new WebAppResourceLoader();
      Configuration cfg = Configuration.defaultConfiguration();
      GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
      Template template = gt.getTemplate(templateFilePath);
      template.binding(data);
      String text = template.render();

      email.setFrom(
          MimeUtility.encodeWord(systemConfig.getShopName())
              + " <"
              + systemConfig.getSmtpFromMail()
              + ">");
      email.setSubject(subject);
      email.setMsg(text);
      email.addTo(toMail);
      email.send();
      isSend = true;
    } catch (EmailException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return isSend;
  }
Ejemplo n.º 15
0
 private static void sendTokenMail(Resource aUser, String aToken) {
   Email confirmationMail = new SimpleEmail();
   try {
     confirmationMail.setMsg("Your new token is " + aToken);
     confirmationMail.setHostName(mConf.getString("mail.smtp.host"));
     confirmationMail.setSmtpPort(mConf.getInt("mail.smtp.port"));
     String smtpUser = mConf.getString("mail.smtp.user");
     String smtpPass = mConf.getString("mail.smtp.password");
     if (!smtpUser.isEmpty()) {
       confirmationMail.setAuthenticator(new DefaultAuthenticator(smtpUser, smtpPass));
     }
     confirmationMail.setSSLOnConnect(mConf.getBoolean("mail.smtp.ssl"));
     confirmationMail.setFrom(
         mConf.getString("mail.smtp.from"), mConf.getString("mail.smtp.sender"));
     confirmationMail.setSubject(i18n.get("user_token_request_subject"));
     confirmationMail.addTo((String) aUser.get("email"));
     confirmationMail.send();
     System.out.println(confirmationMail.toString());
   } catch (EmailException e) {
     e.printStackTrace();
     System.out.println("Failed to send " + aToken + " to " + aUser.get("email"));
   }
 }
Ejemplo n.º 16
0
  public void enviaEmailUsuario() {
    FacesContext context = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
    Usuario usuario = (Usuario) session.getAttribute("usuarioLogado");
    SimpleEmail email = new SimpleEmail();
    // email.setSSLOnConnect(true);
    email.setHostName("smtp-pel.lifemed.com.br");
    //   email.setSslSmtpPort("465");
    email.setSmtpPort(587);
    email.setAuthenticator(new DefaultAuthenticator("anderson.freitas", "nub10fr31t4s"));
    try {
      email.setFrom("*****@*****.**");
      email.setDebug(true);

      email.setSubject(getSubject());
      email.setMsg(mensagem);
      email.addTo(remetente);

      email.send();
    } catch (EmailException ex) {
      ex.printStackTrace();
    }
  }
Ejemplo n.º 17
0
  public void sendHtmlMail(String toEmail, String HtmlMsg) {

    HtmlEmail email = new HtmlEmail();

    email.setCharset("UTF-8");
    email.setHostName("smtp.sina.com");
    email.setSmtpPort(25);
    email.setAuthentication("*****@*****.**", "tianren");
    email.setTLS(true);

    try {
      email.addTo(toEmail);

      email.setFrom("*****@*****.**");
      email.setSubject("Sky Movie"); // Title
      email.setMsg("Ticket Order Info");

      URL url = new URL("http://localhost:8888/TianRen/uploadAd/31049534581071.gif");
      String cid = email.embed(url, "TianRen Logo");

      email.setHtmlMsg(
          "<html><a href='http://localhost:8888/TianRen/index.jsp'><img src=\"cid:"
              + cid
              + "\" height=\"75\"></a><br/>"
              + HtmlMsg
              + "</html>");

      email.send();
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (EmailException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public boolean sendRegistartionConfirmationMail(QuasarMailConfiguration qmc, String... emailids) {
    try {
      HtmlEmail email = new HtmlEmail();
      email.setHostName(qmc.getHost());
      email.setSmtpPort(Integer.parseInt(qmc.getPort()));
      email.setAuthentication(qmc.getAdimnusername(), qmc.getAdminpassword());
      email.setSSLOnConnect(Boolean.parseBoolean(qmc.getStarttls()));

      email.setFrom(qmc.getAdimnusername());

      email.setSubject("TestMail");

      // MailChimp
      // email.setHtmlMsg("<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Insert
      // title here</title></head><body><table id=\"studentdetail\" style=\"background-color:
      // graytext;font-family: sans-serif;padding: 10px;-webkit-border-radius:
      // 4px;-moz-border-radius: 4px;border-radius: 4px;box-shadow: 0 4px 4px -4px rgba(0, 0, 0,
      // 0.7);-moz-box-shadow: 0 4px 4px -4px rgba(0, 0, 0, 0.7);-webkit-box-shadow: 0 4px 6px -5px
      // rgba(0, 0, 0, 0.8);\"><tr><td align=\"center\"><img alt=\"alt\"
      // src=\"images/logo.png\"></td><td align=\"left\">CMC LTD,New Delhi,Near Kohat Enclave Metro
      // Station</td></tr><tr><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<p>Grettings, Thanks for registering
      // at CMC Delhi. We wish you a prosperous learning.If you any query click on this link <a
      // href=\"www.cmcdelhi.com\">Link</a></p></td></tr></table></body></html>");
      email.setHtmlMsg(
          "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Insert title here</title></head><body>"
              + "<table align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" height=\"100%\" width=\"100%\" style=\"border-collapse:collapse;margin:0;padding:0;background-color:#f2f2f2;height:100%!important;width:100%!important\"><tbody><tr><td align=\"center\" valign=\"top\" style=\"margin:0;padding:0;border-top:5px none #aaaaaa;height:100%!important;width:100%!important\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"border-collapse:collapse\"><tbody>"
              + "<tr><td align=\"center\" valign=\"top\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"border-collapse: collapse; background-color: #ffffff; border-top: 0; border-bottom: 0\"><tbody><tr><td align=\"center\" valign=\"top\">"
              + "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\"style=\"border-collapse: collapse\"><tbody>	<tr><td valign=\"top\" style=\"padding-top: 10px; padding-bottom: 10px\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"border-collapse: collapse\">"
              + "<tbody><tr><td valign=\"top\" style=\"padding: 9px\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"width=\"100%\" style=\"border-collapse: collapse\"><tbody><tr><td valign=\"top\" style=\"padding: 9px\"><table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse: collapse\"><tbody><tr><td valign=\"top\"><ahref=\"http://www.cmcdelhi.com/\" "
              + "title=\"\" style=\"word-wrap: break-word\" target=\"_blank\"><img alt=\"\" src=\"https://ci6.googleusercontent.com/proxy/RuvteIJkgNFYdxI6145X-lK4685AcOQxFui4iZxVKwtCz-hegVDIxdtSQ5PaGoE4fLQ_CR3uYlTuRNK8beuUu2loSM5gODacK1JsUqlEZ2lW2plIlZyyKfBPpqg6wpNywbTmDYca7UhlSa20h1k82LH1zIrVEMkqneme9Q=s0-d-e1-ft#http://gallery.mailchimp.com/38e8f39f127b52b8859e52f7c/images/4ea87a8b-6945-477c-904b-bbce8bf80a91.jpg\" width=\"116\" style=\"max-width: 116px; border: 0; outline: none; text-decoration: none; vertical-align: bottom\"></a></td></tr></tbody></table><table align=\"right\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"176\"style=\"border-collapse: collapse\"><tbody><tr><td valign=\"top\" style=\"font-family: Georgia, Times, 'Times New Roman', serif; font-size: 9px; font-style: normal; text-align: center; color: #606060; line-height: 150%\"><spanstyle=\"color: #000000; font-family: arial, helvetica, clean, sans-serif; font-size: small; line-height: 16.003000259399414px; text-align: -webkit-center\">8,Vaishali Enclave,Main Metro Road,&nbsp;</span><br style=\"font-size: small; color: #000000; font-family: arial, helvetica, clean, sans-serif; line-height: 16.003000259399414px; text-align: -webkit-center\">"
              + "<span style=\"color: #000000; font-family: arial, helvetica, clean, sans-serif; font-size: small; line-height: 16.003000259399414px; text-align: -webkit-center\">PitamPura,(Opp. Metro Pillar No. 351), New Delhi-110034,</span><br style=\"font-size: small; color: #000000; font-family: arial, helvetica, clean, sans-serif; line-height: 16.003000259399414px; text-align: -webkit-center\"><span style=\"color: #000000; font-family: arial, helvetica, clean, sans-serif; font-size: small; line-height: 16.003000259399414px; text-align: -webkit-center\">India</span></td></tr></tbody>	</table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr>"
              + "<tr><td align=\"center\" valign=\"top\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"border-collapse:collapse;background-color:#ffffff;border-top:0;border-bottom:0\"><tbody><tr><td align=\"center\" valign=\"top\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse\"><tbody><tr><td valign=\"top\" style=\"padding-top:10px;padding-bottom:10px\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"border-collapse:collapse\"><tbody><tr><td valign=\"top\"><table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse\"><tbody><tr> <td valign=\"top\" style=\"padding:9px 18px;font-size:9px;color:#606060;font-family:Helvetica;line-height:150%;text-align:left\">"
              + "<h1 style=\"margin:0;padding:0;display:block;font-family:Helvetica;font-size:32px;font-style:normal;font-weight:bold;line-height:125%;letter-spacing:-1px;text-align:left;color:#606060!important\">Greetings From CMC Delhi</h1><h3 style=\"margin:0;padding:0;display:block;font-family:Helvetica;font-size:14px;font-style:normal;font-weight:bold;line-height:125%;letter-spacing:-.5px;text-align:left;color:#606060!important\">Registration Confirmation Email</h3><p style=\"margin:1em 0;padding:0;color:#606060;font-family:Helvetica;font-size:15px;line-height:150%;text-align:left\">Thanks for registering at CMC Delhi.This is system generated mail confirming your registration for course #####.Wishing you a prosperous learning.<br>Get your payment details here &lt;a href=\"<a href=\"http://www.cmcdelhi.com\" target=\"_blank\">www.cmcdelhi.com</a>\"</p>"
              + "<p style=\"margin:1em 0;padding:0;color:#606060;font-family:Helvetica;font-size:15px;line-height:150%;text-align:left\">Need inspiration for your design? <a href=\"http://inspiration.mailchimp.com\" style=\"word-wrap:break-word;color:#6dc6dd;font-weight:normal;text-decoration:underline\" target=\"_blank\">Here�s what other MailChimp users are doing.</a></p></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr>"
              + "<tr><td align=\"center\" valign=\"top\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"border-collapse:collapse;background-color:#f2f2f2;border-top:0;border-bottom:0\"><tbody><tr><td align=\"center\" valign=\"top\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse\"><tbody><tr><td valign=\"top\" style=\"padding-top:10px;padding-bottom:10px\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" style=\"border-collapse:collapse\"><tbody><tr><td valign=\"top\"><table align=\"left\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"600\" style=\"border-collapse:collapse\"><tbody><tr>"
              + "<td valign=\"top\" style=\"padding-top:9px;padding-right:18px;padding-bottom:9px;padding-left:18px;color:#606060;font-family:Helvetica;font-size:11px;line-height:125%;text-align:left\"><em>Copyright � *|####YEAR#####|* CMC Delhi, All rights reserved.</em><br><br><strong>Our address :</strong><br><span style=\"color:#000000;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center\">8,Vaishali Enclave,Main Metro Road,&nbsp;</span><br style=\"color:#000000;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center\"><span style=\"color:#000000;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center\">"
              + "Pitam Pura,(Opp. Metro Pillar No. 351), New Delhi-110034,</span><br style=\"color:#000000;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center\"><span style=\"color:#000000;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center\">India</span><br><strong style=\"color:#000000;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center\">For Corporate Queries/College Tie-ups :&nbsp;Ashish Arora&nbsp; (09810324822)&nbsp;</strong><br style=\"color:#000000;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center\">"
              + "<strong style=\"color:#000000;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center\">For Student Queries:&nbsp;</strong><span style=\"color:#000000;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center\">Ms. Sabia Rais / Ms. Priyanka:09313877528, 01165905335 &amp; 65655335</span><br><strong style=\"color:#000000;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center\">E-mail:</strong><a href=\"mailto:[email protected]\" style=\"color:blue;text-decoration:none;font-weight:bold;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center;word-wrap:break-word\" target=\"_blank\">"
              + "[email protected]</a><span style=\"color:#000000;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center\">/</span><a href=\"mailto:[email protected]\" style=\"color:blue;text-decoration:none;font-weight:bold;font-family:arial,helvetica,clean,sans-serif;font-size:small;line-height:16.003000259399414px;text-align:-webkit-center;word-wrap:break-word\" target=\"_blank\">ashis<wbr>[email protected]</a><br>&nbsp;</td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr></tbody></table></td></tr>"
              + "</tbody></table></body></html>");
      // /Email Attachment
      // EmailAttachment attachment = new EmailAttachment();
      // attachment.setPath("/home/guffy/Pictures/fggsa.jpg");
      // attachment.setDisposition(EmailAttachment.ATTACHMENT);
      // attachment.setDescription("Picture of JMosque");
      // attachment.setName("Mousque");

      // email.attach(attachment);

      // set the alternative message
      email.setTextMsg("Your email client does not support HTML messages");

      // adding up the recivers
      for (String em : emailids) {
        // email.addTo("*****@*****.**");
        email.addTo(em);
      }

      email.send();

      return true;

    } catch (EmailException e) {
      Log.e("Email Exception : " + e.getMessage());

    } catch (Exception e) {
      Log.e("Exception : " + e.getMessage());
    }
    return false;
  }
  private MultiPartEmail constructMessage(
      Content contentNode,
      List<String> recipients,
      javax.jcr.Session session,
      org.sakaiproject.nakamura.api.lite.Session sparseSession)
      throws EmailDeliveryException, StorageClientException, AccessDeniedException,
          PathNotFoundException, RepositoryException {
    MultiPartEmail email = new MultiPartEmail();
    // TODO: the SAKAI_TO may make no sense in an email context
    // and there does not appear to be any distinction between Bcc and To in java mail.

    Set<String> toRecipients = new HashSet<String>();
    Set<String> bccRecipients = new HashSet<String>();
    for (String r : recipients) {
      bccRecipients.add(convertToEmail(r.trim(), sparseSession));
    }

    if (contentNode.hasProperty(MessageConstants.PROP_SAKAI_TO)) {
      String[] tor =
          StringUtils.split((String) contentNode.getProperty(MessageConstants.PROP_SAKAI_TO), ',');
      for (String r : tor) {
        r = convertToEmail(r.trim(), sparseSession);
        if (bccRecipients.contains(r)) {
          toRecipients.add(r);
          bccRecipients.remove(r);
        }
      }
    }
    for (String r : toRecipients) {
      try {
        email.addTo(convertToEmail(r, sparseSession));
      } catch (EmailException e) {
        throw new EmailDeliveryException(
            "Invalid To Address [" + r + "], message is being dropped :" + e.getMessage(), e);
      }
    }
    for (String r : bccRecipients) {
      try {
        email.addBcc(convertToEmail(r, sparseSession));
      } catch (EmailException e) {
        throw new EmailDeliveryException(
            "Invalid Bcc Address [" + r + "], message is being dropped :" + e.getMessage(), e);
      }
    }

    if (contentNode.hasProperty(MessageConstants.PROP_SAKAI_FROM)) {
      String from = (String) contentNode.getProperty(MessageConstants.PROP_SAKAI_FROM);
      try {
        email.setFrom(convertToEmail(from, sparseSession));
      } catch (EmailException e) {
        throw new EmailDeliveryException(
            "Invalid From Address [" + from + "], message is being dropped :" + e.getMessage(), e);
      }
    } else {
      throw new EmailDeliveryException("Must provide a 'from' address.");
    }

    if (contentNode.hasProperty(MessageConstants.PROP_SAKAI_BODY)) {
      String messageBody = (String) contentNode.getProperty(MessageConstants.PROP_SAKAI_BODY);
      // if this message has a template, use it
      LOGGER.debug(
          "Checking for sakai:templatePath and sakai:templateParams properties on the outgoing message's node.");
      if (contentNode.hasProperty(MessageConstants.PROP_TEMPLATE_PATH)
          && contentNode.hasProperty(MessageConstants.PROP_TEMPLATE_PARAMS)) {
        Map<String, String> parameters =
            getTemplateProperties(
                (String) contentNode.getProperty(MessageConstants.PROP_TEMPLATE_PARAMS));
        String templatePath = (String) contentNode.getProperty(MessageConstants.PROP_TEMPLATE_PATH);
        LOGGER.debug("Got the path '{0}' to the template for this outgoing message.", templatePath);
        Node templateNode = session.getNode(templatePath);
        if (templateNode.hasProperty("sakai:template")) {
          String template = templateNode.getProperty("sakai:template").getString();
          LOGGER.debug("Pulled the template body from the template node: {0}", template);
          messageBody = templateService.evaluateTemplate(parameters, template);
          LOGGER.debug("Performed parameter substitution in the template: {0}", messageBody);
        }
      } else {
        LOGGER.debug(
            "Message node '{0}' does not have sakai:templatePath and sakai:templateParams properties",
            contentNode.getPath());
      }
      try {
        email.setMsg(messageBody);
      } catch (EmailException e) {
        throw new EmailDeliveryException(
            "Invalid Message Body, message is being dropped :" + e.getMessage(), e);
      }
    }

    if (contentNode.hasProperty(MessageConstants.PROP_SAKAI_SUBJECT)) {
      email.setSubject((String) contentNode.getProperty(MessageConstants.PROP_SAKAI_SUBJECT));
    }

    ContentManager contentManager = sparseSession.getContentManager();
    for (String streamId : contentNode.listStreams()) {
      String description = null;
      if (contentNode.hasProperty(
          StorageClientUtils.getAltField(
              MessageConstants.PROP_SAKAI_ATTACHMENT_DESCRIPTION, streamId))) {
        description =
            (String)
                contentNode.getProperty(
                    StorageClientUtils.getAltField(
                        MessageConstants.PROP_SAKAI_ATTACHMENT_DESCRIPTION, streamId));
      }
      LiteEmailDataSource ds = new LiteEmailDataSource(contentManager, contentNode, streamId);
      try {
        email.attach(ds, streamId, description);
      } catch (EmailException e) {
        throw new EmailDeliveryException(
            "Invalid Attachment [" + streamId + "] message is being dropped :" + e.getMessage(), e);
      }
    }
    return email;
  }
  @SuppressWarnings("unchecked")
  public void onMessage(Message message) {
    try {
      LOGGER.debug("Started handling email jms message.");

      String nodePath = message.getStringProperty(NODE_PATH_PROPERTY);
      String contentPath = message.getStringProperty(CONTENT_PATH_PROPERTY);
      Object objRcpt = message.getObjectProperty(RECIPIENTS);
      List<String> recipients = null;

      if (objRcpt instanceof List<?>) {
        recipients = (List<String>) objRcpt;
      } else if (objRcpt instanceof String) {
        recipients = new LinkedList<String>();
        String[] rcpts = StringUtils.split((String) objRcpt, ',');
        for (String rcpt : rcpts) {
          recipients.add(rcpt);
        }
      }

      if (contentPath != null && contentPath.length() > 0) {
        javax.jcr.Session adminSession = repository.loginAdministrative(null);
        org.sakaiproject.nakamura.api.lite.Session sparseSession =
            StorageClientUtils.adaptToSession(adminSession);

        try {
          ContentManager contentManager = sparseSession.getContentManager();
          Content messageContent = contentManager.get(contentPath);

          if (objRcpt != null) {
            // validate the message
            if (messageContent != null) {
              if (messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX)
                  && (MessageConstants.BOX_OUTBOX.equals(
                          messageContent.getProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX))
                      || MessageConstants.BOX_PENDING.equals(
                          messageContent.getProperty(MessageConstants.PROP_SAKAI_MESSAGEBOX)))) {
                if (messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) {
                  // We're retrying this message, so clear the errors
                  messageContent.setProperty(
                      MessageConstants.PROP_SAKAI_MESSAGEERROR, (String) null);
                }
                if (messageContent.hasProperty(MessageConstants.PROP_SAKAI_TO)
                    && messageContent.hasProperty(MessageConstants.PROP_SAKAI_FROM)) {
                  // make a commons-email message from the message
                  MultiPartEmail email = null;
                  try {
                    email =
                        constructMessage(messageContent, recipients, adminSession, sparseSession);

                    email.setSmtpPort(smtpPort);
                    email.setHostName(smtpServer);

                    email.send();
                  } catch (EmailException e) {
                    String exMessage = e.getMessage();
                    Throwable cause = e.getCause();

                    setError(messageContent, exMessage);
                    LOGGER.warn("Unable to send email: " + exMessage);

                    // Get the SMTP error code
                    // There has to be a better way to do this
                    boolean rescheduled = false;
                    if (cause != null && cause.getMessage() != null) {
                      String smtpError = cause.getMessage().trim();
                      try {
                        int errorCode = Integer.parseInt(smtpError.substring(0, 3));
                        // All retry-able SMTP errors should have codes starting
                        // with 4
                        scheduleRetry(errorCode, messageContent);
                        rescheduled = true;
                      } catch (NumberFormatException nfe) {
                        // smtpError didn't start with an error code, let's dig for
                        // it
                        String searchFor = "response:";
                        int rindex = smtpError.indexOf(searchFor);
                        if (rindex > -1 && (rindex + searchFor.length()) < smtpError.length()) {
                          int errorCode =
                              Integer.parseInt(
                                  smtpError.substring(searchFor.length(), searchFor.length() + 3));
                          scheduleRetry(errorCode, messageContent);
                          rescheduled = true;
                        }
                      }
                    }
                    if (rescheduled) {
                      LOGGER.info("Email {} rescheduled for redelivery. ", nodePath);
                    } else {
                      LOGGER.error("Unable to reschedule email for delivery: " + e.getMessage(), e);
                    }
                  }
                } else {
                  setError(messageContent, "Message must have a to and from set");
                }
              } else {
                setError(messageContent, "Not an outbox");
              }
              if (!messageContent.hasProperty(MessageConstants.PROP_SAKAI_MESSAGEERROR)) {
                messageContent.setProperty(
                    MessageConstants.PROP_SAKAI_MESSAGEBOX, MessageConstants.BOX_SENT);
              }
            }
          } else {
            String retval = "null";
            setError(
                messageContent,
                "Expected recipients to be String or List<String>.  Found " + retval);
          }
        } finally {
          if (adminSession != null) {
            adminSession.logout();
          }
        }
      }
    } catch (PathNotFoundException e) {
      LOGGER.error(e.getMessage(), e);
    } catch (RepositoryException e) {
      LOGGER.error(e.getMessage(), e);
    } catch (JMSException e) {
      LOGGER.error(e.getMessage(), e);
    } catch (EmailDeliveryException e) {
      LOGGER.error(e.getMessage());
    } catch (ClientPoolException e) {
      LOGGER.error(e.getMessage(), e);
    } catch (StorageClientException e) {
      LOGGER.error(e.getMessage(), e);
    } catch (AccessDeniedException e) {
      LOGGER.error(e.getMessage(), e);
    }
  }