/** Return the content. */
 public Object getContent(DataSource ds) throws IOException {
   // create a new DeliveryStatus
   try {
     /*
        Session session;
        if (ds instanceof MessageAware) {
     javax.mail.MessageContext mc =
     	((MessageAware)ds).getMessageContext();
     session = mc.getSession();
        } else {
     // Hopefully a rare case.  Also hopefully the application
     // has created a default Session that can just be returned
     // here.  If not, the one we create here is better than
     // nothing, but overall not a really good answer.
     session = Session.getDefaultInstance(new Properties(), null);
        }
        return new DeliveryStatus(session, ds.getInputStream());
        */
     return new DeliveryStatus(ds.getInputStream());
   } catch (MessagingException me) {
     throw new IOException(
         "Exception creating DeliveryStatus in "
             + "message/delivery-status DataContentHandler: "
             + me.toString());
   }
 }
  @Override
  public void sendMail(boolean isByDepartment, String logsRow, Message message) {
    synchronized (this) {
      // Initialize the Logs Status Attributes
      String status = "Failed Sending TimeSheet";
      String recipient = null;

      try {

        recipient = message.getRecipients(Message.RecipientType.TO)[0].toString();

        logger.info("NOW SENDING MESSAGE TO: " + recipient);

        Transport.send(message);

        status = "Successed Sending TimeSheet";

        logger.info(status + " TO: " + recipient);

      } catch (MessagingException e1) {

        logger.info("Error On Transporting Message: " + e1.toString());
        status = "Failed Sending TimeSheet";
        logger.info(status + " TO: " + recipient);
      }

      if (isByDepartment) {

        try {

          statusQuery.setString(1, logsRow);

          statusQuery.setString(2, recipient);

          statusQuery.setString(3, status);

          statusQuery.addBatch();

        } catch (SQLException e) {

          System.out.println("Error on Preparing the parameters of Log Query: " + e.toString());
        }
      }
    }
  }
示例#3
0
  // multiple email recipients
  public static String SendEmail(
      String fromEmail, ArrayList<String> toEmail, String subject, String body) {

    String errorMessage = null;

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    // need try / catch for invalid email field trapping
    try {

      Message msg = new MimeMessage(session);

      // set from email address :
      // this must be an admin of the system OR the currently logged
      // in user
      msg.setFrom(new InternetAddress(fromEmail));

      // build a list of one or more recipients
      for (String addr : toEmail) {
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(addr));
      }

      // add subject and body
      msg.setSubject(subject);
      msg.setText(body);

      // attempt the send
      Transport.send(msg);

    } catch (AddressException e) {
      log.info(e.toString());
      errorMessage = "An Incorrect Recipient Email address was supplied.";
    } catch (MessagingException e) {
      log.info(e.toString());
      errorMessage =
          "There was a problem with the email server.  Please contact the recipients directly.";
    }

    return errorMessage;
  }
示例#4
0
  /**
   * Methode pour l'envoi d'un mail au format HTML.
   *
   * @param a_from L'expediteur du mail.
   * @param a_subject Le sujet du mail.
   * @param a_to Le destinataire du mail.
   * @param a_message Le contenu du mail au format HTML.
   * @throws Exception Si une erreur survient.
   */
  public void sendMailHTML(String a_from, String a_subject, String a_to, String a_message)
      throws Exception {
    if (isLoggingDebug()) {
      logDebug(CastoConstantes.METHODE_ENTREE + "com.castorama.utils.MailUtils.sendMailHTML().");
    }

    EmailEvent l_emailEvent = null;

    try {
      // Creation de l'objet mail
      Message l_msg = MimeMessageUtils.createMessage(a_from, a_subject);

      // On fixe le destinataire du mail
      MimeMessageUtils.setRecipient(l_msg, Message.RecipientType.TO, a_to);

      // On fixe le message
      ContentPart[] l_content = {
        new ContentPart(a_message, "text/html"),
      };

      MimeMessageUtils.setContent(l_msg, l_content);

      // Envoi du mail
      l_emailEvent = new EmailEvent(l_msg);
      l_emailEvent.setCharSet("UTF-8");

      getListener().sendEmailEvent(l_emailEvent);
    } catch (MessagingException l_exception) {
      logError("Impossible d'envoyer le mail : " + a_subject + ", " + l_exception.toString());

      throw l_exception;
    } catch (EmailException l_emailException) {
      logError("Impossible d'envoyer le mail : " + a_subject + ", " + l_emailException.toString());

      throw l_emailException;
    }

    if (isLoggingDebug()) {
      logDebug(CastoConstantes.METHODE_SORTIE + "com.castorama.utils.MailUtils.sendMailHTML().");
    }
  }
示例#5
0
  public void sendMail() {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String msgBody = "...This is a test mail";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "Example.com Admin"));
      msg.addRecipient(
          Message.RecipientType.TO, new InternetAddress("*****@*****.**", "Malith"));
      msg.setSubject("Your Example.com account has been activated");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (AddressException e) {
      System.out.println(e.toString());
    } catch (MessagingException e) {
      System.out.println(e.toString());
    } catch (UnsupportedEncodingException ex) {
      Logger.getLogger(MyEmail.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
示例#6
0
 /** Description of the Method */
 public boolean sendMessage() {
   MimeMultipart mp = new MimeMultipart();
   try {
     // if there is a text and an html section
     if (sendingText.getCount() > 1) {
       sendingText.setSubType("alternative");
     }
     // if we are sending attachments
     if (sendingAttachments.getCount() > 0) {
       MimeBodyPart bp = new MimeBodyPart();
       bp.setContent(sendingAttachments);
       mp.addBodyPart(bp, 0);
       bp = new MimeBodyPart();
       bp.setContent(sendingText);
       mp.addBodyPart(bp, 0);
     } else {
       mp = sendingText;
     }
     Logger.debug(this, "Getting the MailContext.");
     /*
      *
      * Get the mail session from
      *
      * the container Context
      */
     Session session = null;
     Context ctx = null;
     try {
       ctx = (Context) new InitialContext().lookup("java:comp/env");
       session = (javax.mail.Session) ctx.lookup("mail/MailSession");
     } catch (Exception e1) {
       try {
         Logger.debug(this, "Using the jndi intitialContext().");
         ctx = new InitialContext();
         session = (javax.mail.Session) ctx.lookup("mail/MailSession");
       } catch (Exception e) {
         Logger.error(this, "Exception occured finding a mailSession in JNDI context.");
         Logger.error(this, e1.getMessage(), e1);
         return false;
       }
     }
     if (session == null) {
       Logger.debug(this, "No Mail Session Available.");
       return false;
     }
     Logger.debug(
         this, "Delivering mail using: " + session.getProperty("mail.smtp.host") + " as server.");
     MimeMessage message = new MimeMessage(session);
     message.addHeader("X-RecipientId", String.valueOf(getRecipientId()));
     if ((fromEmail != null) && (fromName != null) && (0 < fromEmail.trim().length())) {
       message.setFrom(new InternetAddress(fromEmail, fromName));
     } else if ((fromEmail != null) && (0 < fromEmail.trim().length())) {
       message.setFrom(new InternetAddress(fromEmail));
     }
     if (toName != null) {
       String[] recipients = toEmail.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient, toName));
       }
     } else {
       String[] recipients = toEmail.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
       }
     }
     if (UtilMethods.isSet(cc)) {
       String[] recipients = cc.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.CC, new InternetAddress(recipient));
       }
     }
     if (UtilMethods.isSet(bcc)) {
       String[] recipients = bcc.split("[;,]");
       for (String recipient : recipients) {
         message.addRecipient(Message.RecipientType.BCC, new InternetAddress(recipient));
       }
     }
     message.setSubject(subject, encoding);
     message.setContent(mp);
     Transport.send(message);
     result = "Send Ok";
     return true;
   } catch (javax.mail.SendFailedException f) {
     String error = String.valueOf(f);
     errorMessage =
         error.substring(
             error.lastIndexOf("javax.mail.SendFailedException:")
                 + "javax.mail.SendFailedException:".length(),
             (error.length() - 1));
     result = "Failed:" + error;
     Logger.error(Mailer.class, f.toString(), f);
     return false;
   } catch (MessagingException f) {
     String error = String.valueOf(f);
     errorMessage =
         error.substring(
             error.lastIndexOf("javax.mail.MessagingException:")
                 + "javax.mail.MessagingException:".length(),
             (error.length() - 1));
     result = "Failed:" + error;
     Logger.error(Mailer.class, f.toString(), f);
     return false;
   } catch (UnsupportedEncodingException f) {
     String error = String.valueOf(f);
     errorMessage =
         error.substring(
             error.lastIndexOf("java.io.UnsupportedEncodingException:")
                 + "java.io.UnsupportedEncodingException:".length(),
             (error.length() - 1));
     result = "Failed:" + error;
     Logger.error(Mailer.class, f.toString(), f);
     return false;
   }
 }
示例#7
0
  public static String send(Email2Send email, Server server) throws Exception {
    Session session;

    if (server.isAuth()) {
      Authenticator auth = new PopAuthenticator(server.getUser(), server.getPwd());
      session = Session.getInstance(getProperties(server), auth);
    } else {
      session = Session.getInstance(getProperties(server), null);
    }
    MyMessage mailMsg = new MyMessage(session); // a new email message
    InternetAddress[] addresses = null;
    try {
      if (email.getDestinatari() != null && email.getDestinatari().size() > 0) {
        addresses = InternetAddress.parse(email.getDestinatariToString(), false);
        mailMsg.setRecipients(Message.RecipientType.TO, addresses);
      } else {
        throw new MessagingException("The mail message requires a 'To' address.");
      }
      if (email.getCc() != null && email.getCc().size() > 0) {
        addresses = InternetAddress.parse(email.getCcToString(), false);
        mailMsg.setRecipients(Message.RecipientType.CC, addresses);
      }
      if (email.getBcc() != null && email.getBcc().size() > 0) {
        addresses = InternetAddress.parse(email.getBccToString(), false);
        mailMsg.setRecipients(Message.RecipientType.BCC, addresses);
      }
      if (email.getMittente() != null) {
        mailMsg.setFrom(new InternetAddress(email.getMittente()));
      } else {
        throw new MessagingException("The mail message requires a valid 'From' address.");
      }
      //
      if (email.getOggetto() != null) mailMsg.setSubject(email.getOggetto());
      // corpo e attachment
      if (email.getAllegati() != null && email.getAllegati().size() > 0) {
        BodyPart messageBodyPart = new MimeBodyPart();
        if (email.getCorpo() != null) messageBodyPart.setText(email.getCorpo());
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // attachment
        for (File allegato : email.getAllegati()) {
          messageBodyPart = new MimeBodyPart();
          DataSource source = new FileDataSource(allegato.getCanonicalPath());
          DataHandler dataH = new DataHandler(source);
          messageBodyPart.setDataHandler(dataH);
          messageBodyPart.setFileName(allegato.getName());
          multipart.addBodyPart(messageBodyPart);
        }
        mailMsg.setContent(multipart);
      } else {
        mailMsg.setContent(email.getCorpo(), "text/plain;charset=\"UTF-8\"");
      }

      mailMsg.setId("<CN" + System.currentTimeMillis() + "@giava.by/giavacms>");
      // mailMsg.addHeader("Message-ID",
      // "111111.11199295388525.provaProvaProva");

      mailMsg.setSentDate(new Date());
      mailMsg.saveChanges();
      // Finally, send the mail message; throws a 'SendFailedException'
      // if any of the message's recipients have an invalid address
      Transport.send(mailMsg);
    } catch (MessagingException e) {
      logger.error(e.toString());
      e.printStackTrace();
      return "";
    } catch (Exception exc) {
      logger.error(exc.toString());
      exc.printStackTrace();
      return "";
    }
    return mailMsg.getMessageID();
  }
示例#8
0
  private String sendEmail(Map notupMap, String email) {
    String err = "";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // departClass, deptClassName, cscode, cscodeName, teacherID, teacherName, memo
    // String teacherId = notupMap.get("teacherId").toString();
    String teacherName = notupMap.get("teacherName").toString();
    String deptClassName = notupMap.get("deptClassName").toString();
    String cscodeName = notupMap.get("cscodeName").toString();
    String endDate = df.format(endCal.getTime());
    // List<Map> notupList = (List<Map>)notupMap.get("notUploadList");
    // String[] weeks = {"(一)","(二)","(三)","(四)","(五)","(六)","(日)"};

    InternetAddress[] address = null;
    boolean sessionDebug = false;
    String mailserver = IConstants.MAILSERVER_DOMAIN_NAME_WWW;
    String From = "*****@*****.**";
    String to = email;
    String sysAdmin = "*****@*****.**";
    // String to = "*****@*****.**";
    String Subject = "";
    String type = "text/html";

    if (level.equals("1")) {
      Subject = "中華科技大學[期中考成績]未上傳到期前三天提醒通知! 截止日期:" + endDate;
    } else if (level.equals("2")) {
      if (scope.equals("2")) {
        Subject = "中華科技大學[畢業班 期末考成績]未上傳到期前一天提醒通知! 截止日期:" + endDate;
      } else {
        Subject = "中華科技大學[期末考成績]未上傳到期前一天提醒通知! 截止日期:" + endDate;
      }
    }
    String message = "<b>" + teacherName + "&nbsp;老師  您好:<br>";
    message += "您尚有:" + deptClassName + "  " + cscodeName + " ,成績未上傳!!!<br>";
    /*
    for(Map ntMap:notupList){
    	message += ntMap.get("deptClassName").toString() + "&nbsp;&nbsp;";
    	message += ntMap.get("subjectName").toString() + "<br>";
    }
    */
    message += "<br><font color=red>請您務必記得於截止日:" + endDate + " 前上傳成績!!!</font><br>";
    message += "<br><font color=blue>這封E-mail是由成績系統發送的,請勿回覆!!!</font><br>";
    message +=
        "<br><font color=\"#0000FF\" face=\"新細明體\" style=\"font-weight:500;\">中華科技大學 教務單位</font>";

    try {
      // log.debug("send email from:" + From + "\n To:" + to + "\n: mesg:" + message);
      Properties props = System.getProperties();
      props.put("mail.smtp.host", mailserver);
      props.put("mail.debug", true);
      props.put("mail.transport.protocol", "smtp");
      props.put("mail.smtp.auth", "true");
      Authenticator auth = new SMTPAuthenticator();

      javax.mail.Session mailSession = javax.mail.Session.getDefaultInstance(props, auth);
      mailSession.setDebug(sessionDebug);
      MimeMessage msg = new MimeMessage(mailSession);

      msg.setFrom(new InternetAddress(From));
      address = InternetAddress.parse(to, false);
      msg.setRecipients(Message.RecipientType.TO, address);
      msg.setSubject(Subject);
      msg.setSentDate(new Date());
      // msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(sysAdmin, false));

      Multipart mp = new MimeMultipart();
      MimeBodyPart mbp = new MimeBodyPart();
      // mbp.setContent(message, type+";charset=MS950");
      mbp.setContent(message, type + ";charset=UTF-8");
      mp.addBodyPart(mbp);
      // msg.setContent(mp, type+";charset=MS950");
      msg.setContent(mp, type + ";charset=UTF-8");
      // Store store = mailSession.getStore("pop3");
      // store.connect("seastar.com.tw", "mailer", "emai168mvc");
      Transport transport = mailSession.getTransport();
      transport.connect();
      Transport.send(msg);
      transport.close();
      // store.close();

    } catch (MessagingException mex) {
      err = mex.toString();
      mex.printStackTrace();
      return err;
    }
    return err;
  }
  /** @see org.apache.avalon.framework.activity.Initializable#initialize() */
  public void initialize() throws Exception {

    getLogger().info("JamesSpoolManager init...");
    spool = (SpoolRepository) compMgr.lookup(SpoolRepository.ROLE);

    MailetLoader mailetLoader = (MailetLoader) compMgr.lookup(MailetLoader.ROLE);
    MatcherLoader matchLoader = (MatcherLoader) compMgr.lookup(MatcherLoader.ROLE);

    // A processor is a Collection of
    processors = new HashMap();

    final Configuration[] processorConfs = conf.getChildren("processor");
    for (int i = 0; i < processorConfs.length; i++) {
      Configuration processorConf = processorConfs[i];
      String processorName = processorConf.getAttribute("name");
      try {
        LinearProcessor processor = new LinearProcessor();
        setupLogger(processor, processorName);
        processor.setSpool(spool);
        processor.initialize();
        processors.put(processorName, processor);

        final Configuration[] mailetConfs = processorConf.getChildren("mailet");
        // Loop through the mailet configuration, load
        // all of the matcher and mailets, and add
        // them to the processor.
        for (int j = 0; j < mailetConfs.length; j++) {
          Configuration c = mailetConfs[j];
          String mailetClassName = c.getAttribute("class");
          String matcherName = c.getAttribute("match");
          Mailet mailet = null;
          Matcher matcher = null;
          try {
            matcher = matchLoader.getMatcher(matcherName);
            // The matcher itself should log that it's been inited.
            if (getLogger().isInfoEnabled()) {
              StringBuffer infoBuffer =
                  new StringBuffer(64)
                      .append("Matcher ")
                      .append(matcherName)
                      .append(" instantiated.");
              getLogger().info(infoBuffer.toString());
            }
          } catch (MessagingException ex) {
            // **** Do better job printing out exception
            if (getLogger().isErrorEnabled()) {
              StringBuffer errorBuffer =
                  new StringBuffer(256)
                      .append("Unable to init matcher ")
                      .append(matcherName)
                      .append(": ")
                      .append(ex.toString());
              getLogger().error(errorBuffer.toString(), ex);
              if (ex.getNextException() != null) {
                getLogger().error("Caused by nested exception: ", ex.getNextException());
              }
            }
            System.err.println("Unable to init matcher " + matcherName);
            System.err.println("Check spool manager logs for more details.");
            // System.exit(1);
            throw ex;
          }
          try {
            mailet = mailetLoader.getMailet(mailetClassName, c);
            if (getLogger().isInfoEnabled()) {
              StringBuffer infoBuffer =
                  new StringBuffer(64)
                      .append("Mailet ")
                      .append(mailetClassName)
                      .append(" instantiated.");
              getLogger().info(infoBuffer.toString());
            }
          } catch (MessagingException ex) {
            // **** Do better job printing out exception
            if (getLogger().isErrorEnabled()) {
              StringBuffer errorBuffer =
                  new StringBuffer(256)
                      .append("Unable to init mailet ")
                      .append(mailetClassName)
                      .append(": ")
                      .append(ex.toString());
              getLogger().error(errorBuffer.toString(), ex);
              if (ex.getNextException() != null) {
                getLogger().error("Caused by nested exception: ", ex.getNextException());
              }
            }
            System.err.println("Unable to init mailet " + mailetClassName);
            System.err.println("Check spool manager logs for more details.");
            // System.exit(1);
            throw ex;
          }
          // Add this pair to the processor
          processor.add(matcher, mailet);
        }

        // Close the processor matcher/mailet lists.
        //
        // Please note that this is critical to the proper operation
        // of the LinearProcessor code.  The processor will not be
        // able to service mails until this call is made.
        processor.closeProcessorLists();

        if (getLogger().isInfoEnabled()) {
          StringBuffer infoBuffer =
              new StringBuffer(64)
                  .append("Processor ")
                  .append(processorName)
                  .append(" instantiated.");
          getLogger().info(infoBuffer.toString());
        }
      } catch (Exception ex) {
        if (getLogger().isErrorEnabled()) {
          StringBuffer errorBuffer =
              new StringBuffer(256)
                  .append("Unable to init processor ")
                  .append(processorName)
                  .append(": ")
                  .append(ex.toString());
          getLogger().error(errorBuffer.toString(), ex);
        }
        throw ex;
      }
    }
    if (getLogger().isInfoEnabled()) {
      StringBuffer infoBuffer =
          new StringBuffer(64)
              .append("Spooler Manager uses ")
              .append(numThreads)
              .append(" Thread(s)");
      getLogger().info(infoBuffer.toString());
    }

    active = true;
    numActive = 0;
    spoolThreads = new java.util.ArrayList(numThreads);
    for (int i = 0; i < numThreads; i++) {
      Thread reader = new Thread(this, "Spool Thread #" + i);
      spoolThreads.add(reader);
      reader.start();
    }
  }