コード例 #1
0
  /** 发�?邮件 */
  public boolean sendOut() {
    try {
      mimeMsg.setContent(mp);
      mimeMsg.saveChanges();
      System.out.println("正在发�?邮件....");

      Session mailSession = Session.getInstance(props, null);
      Transport transport = mailSession.getTransport("smtp");
      transport.connect((String) props.get("mail.smtp.host"), username, password);
      transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
      //          如果抄�?人为null  不添加抄送人
      if (mimeMsg.getRecipients(Message.RecipientType.CC) != null)
        transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));
      // transport.send(mimeMsg);

      System.out.println("发送邮件成功");
      transport.close();

      return true;
    } catch (Exception e) {
      System.err.println("邮件发送失败" + e);
      e.printStackTrace();
      return false;
    }
  }
コード例 #2
0
ファイル: GaeMailService.java プロジェクト: htchepannou/limbe
  // -- MailService overrides
  @Override
  public void send(MailController controller) throws MessagingException {
    if (!controller.hasRecipients()) {
      LOG.warning("Not recipients. No email to send");
      return;
    }

    /* log */

    /* Open the Session */
    Properties properties = new Properties();
    Session session = Session.getInstance(properties, null);
    OptionService os = findService(OptionService.class);
    MimeMessage mm = createMimeMessage(controller, session, os);

    LOG.info("");
    LOG.info(" From:    " + toString(mm.getFrom()));
    LOG.info(" ReplyTo: " + toString(mm.getReplyTo()));
    LOG.info(" Sender:  " + mm.getSender());
    LOG.info(" To:      " + toString(mm.getRecipients(Message.RecipientType.TO)));
    LOG.info(" CC:      " + toString(mm.getRecipients(Message.RecipientType.CC)));
    LOG.info(" Bcc:     " + toString(mm.getRecipients(Message.RecipientType.BCC)));
    LOG.info(" Subject: " + mm.getSubject());
    LOG.info("");

    Transport.send(mm);
  }
コード例 #3
0
ファイル: Emailer.java プロジェクト: baojie1985/MNTG
  public static void sendEmail(
      InternetAddress from, InternetAddress to, String content, String requester)
      throws MessagingException, UnsupportedEncodingException {

    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", SMTP_HOST_NAME);
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("MN Traffic Generation is used by " + requester);
    message.setContent(content, "text/plain");

    message.addRecipient(Message.RecipientType.TO, to);

    InternetAddress[] replyto = new InternetAddress[1];
    replyto[0] = from;

    message.setFrom(from);
    message.setReplyTo(replyto);
    message.setSender(from);

    transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));

    transport.close();
  }
コード例 #4
0
  @Override
  public void run() {
    LOGGER.info("***********Inside send e-Mail Thread************");
    LOGGER.info("Sending email to:: E-mail Address::" + emailModel.getToaddess());
    Session mailSession = createSmtpSession();
    mailSession.setDebug(true);
    List<String> toAddresses = new ArrayList<String>();

    try {
      Transport transport = mailSession.getTransport();
      MimeMessage message = new MimeMessage(mailSession);

      message.setSubject(emailModel.getSubject());
      message.setFrom(new InternetAddress(emailModel.getFromAddress()));
      message.setContent(emailModel.getContent(), "text/html");

      toAddresses.add(emailModel.getToaddess());
      transport.connect();
      Iterator<String> itr = toAddresses.iterator();
      while (itr.hasNext()) {
        String toAddress = (String) itr.next();
        message.addRecipients(Message.RecipientType.TO, toAddress);
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
      }
      LOGGER.info("Successfully sent email to:: E-mail Address::" + emailModel.getToaddess());
    } catch (MessagingException e) {
      LOGGER.error("Cannot Send email", e);
    }
  }
コード例 #5
0
  // send emails
  public void sendEmail(String to, String mess) {

    try {
      String host = "smtp.gmail.com";
      String username = "******";
      String password = "******";
      String email = "*****@*****.**";

      Properties props = System.getProperties();
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.user", username);
      props.put("mail.smtp.password", password);
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");

      Session s = Session.getDefaultInstance(props, null);
      MimeMessage m = new MimeMessage(s);
      m.setFrom(new InternetAddress(email));

      m.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      m.setSubject("Secret Santa");
      m.setText(mess);

      Transport t = s.getTransport("smtp");
      t.connect(host, 465, username, password);
      t.sendMessage(m, m.getRecipients(Message.RecipientType.TO));
      t.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
コード例 #6
0
 public Address[] getBcc() {
   MimeMessage message = getMessage();
   try {
     return message.getRecipients(MimeMessage.RecipientType.BCC);
   } catch (MessagingException e) {
     Debug.logError(e, module);
     return null;
   }
 }
コード例 #7
0
  @Test
  public void shouldNotActivateUser() throws Exception {
    String email = "*****@*****.**";

    UserResult userResult;
    Client client = createClient();
    WebResource webResource = client.resource(ringringServerApi.getUrl() + "/user");

    // Create request hash with email address
    HashMap<String, String> requestHash = new HashMap<String, String>();
    requestHash.put("email", email);

    // First email registration
    userResult =
        webResource
            .type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .post(UserResult.class, requestHash);

    // User needs to registered
    assertEquals(Status.OKAY, userResult.getStatus());
    assertTrue(userResult.isSuccess());

    // Check if email sent to the user
    MimeMessage message = getLastMail().getMimeMessage();
    assertEquals(configManager.getSmtpFrom(), message.getFrom()[0].toString());
    assertEquals(email, message.getRecipients(Message.RecipientType.TO)[0].toString());

    User registeredUser = userResult.getUser();
    assertEquals(email, registeredUser.getEmail());
    assertFalse(registeredUser.getIsActivated());
    assertFalse(registeredUser.getIsLoggedIn());

    // 1st try: email in the path is not matching to the user's email
    webResource = client.resource(ringringServerApi.getUrl() + "/user/[email protected]");
    StatusResult statusResult =
        webResource
            .type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .put(StatusResult.class, registeredUser);

    assertEquals(Status.INVALID_EMAIL, statusResult.getStatus());

    // 2nd try: Incorrect activation code
    registeredUser.setActivationCode("SOME_FALSE_ACTIVATION_CODE");

    webResource =
        client.resource(ringringServerApi.getUrl() + "/user/" + registeredUser.getEmail());
    statusResult =
        webResource
            .type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .put(StatusResult.class, registeredUser);

    assertEquals(Status.INVALID_ACTIVATION_CODE, statusResult.getStatus());
  }
コード例 #8
0
  private void assertMessage(MimeMessage message, BirthdayMessage expected)
      throws MessagingException {
    BirthdayMessage sent =
        new BirthdayMessage(
            GreenMailUtil.getAddressList(message.getFrom()),
            GreenMailUtil.getAddressList(message.getRecipients(Message.RecipientType.TO)),
            message.getSubject(),
            GreenMailUtil.getBody(message));

    assertThat("Message", sent, is(expected));
  }
コード例 #9
0
  /**
   * Set some email's basic information to MailMessage .
   *
   * @param mime
   * @param mailMsg
   * @throws MessagingException
   * @throws ParseException
   */
  private void setMailBasicInfoForMailMsg(MimeMessage mime, MailMessage mailMsg)
      throws MessagingException, ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
    String msgId = mime.getMessageID();
    Address[] from = mime.getFrom();
    Address[] to = mime.getRecipients(RecipientType.TO);
    Address[] cc = mime.getRecipients(RecipientType.CC);
    Address[] bcc = mime.getRecipients(RecipientType.BCC);
    String subject = mime.getSubject();
    Date sendDate = mime.getSentDate();
    String receivedUTCDate = sdf.format(this.resolveReceivedDate(mime));

    mailMsg.setMsgId(msgId);
    mailMsg.setFrom(this.convertToMailAddress(from));
    mailMsg.setTo(this.convertToMailAddress(to));
    mailMsg.setCc(this.convertToMailAddress(cc));
    mailMsg.setBcc(this.convertToMailAddress(bcc));
    mailMsg.setSubject(subject);
    if (sendDate != null) {
      mailMsg.setSendDate(sdf.format(sendDate));
    }
    mailMsg.setReceivedDate(receivedUTCDate);
  }
コード例 #10
0
  @Test
  public void shouldActivateUser() throws Exception {
    String email = "*****@*****.**";

    UserResult userResult;
    Client client = createClient();
    WebResource webResource = client.resource(ringringServerApi.getUrl() + "/user");

    // Create request hash with email address
    HashMap<String, String> requestHash = new HashMap<String, String>();
    requestHash.put("email", email);

    // First email registration
    userResult =
        webResource
            .type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .post(UserResult.class, requestHash);

    // Check if email sent to the user
    MimeMessage message = getLastMail().getMimeMessage();
    assertEquals(configManager.getSmtpFrom(), message.getFrom()[0].toString());
    assertEquals(email, message.getRecipients(Message.RecipientType.TO)[0].toString());

    // User needs to registered
    assertEquals(Status.OKAY, userResult.getStatus());
    assertTrue(userResult.isSuccess());

    User registeredUser = userResult.getUser();
    assertEquals(email, registeredUser.getEmail());
    assertFalse(registeredUser.getIsActivated());
    assertFalse(registeredUser.getIsLoggedIn());

    // The activation code is not sent in the REST response. Get it from the email
    String activationCode = getActivationCodeFromEmailContent(message.getContent().toString());
    registeredUser.setActivationCode(activationCode);

    // Activate the user
    webResource =
        client.resource(ringringServerApi.getUrl() + "/user/" + registeredUser.getEmail());
    StatusResult statusresult =
        webResource
            .type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .put(StatusResult.class, registeredUser);

    assertEquals(Status.OKAY, statusresult.getStatus());
  }
コード例 #11
0
  @Test
  public void shouldRegisterUser() throws Exception {
    String email = "*****@*****.**";

    UserResult userResult;
    Client client = createClient();
    WebResource webResource = client.resource(ringringServerApi.getUrl() + "/user");

    // Create request hash with email address
    HashMap<String, String> requestHash = new HashMap<String, String>();
    requestHash.put("email", email);

    // First email registration
    userResult =
        webResource
            .type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .post(UserResult.class, requestHash);

    // Check if email sent to the user
    MimeMessage message = getLastMail().getMimeMessage();
    assertEquals(configManager.getSmtpFrom(), message.getFrom()[0].toString());
    assertEquals(email, message.getRecipients(Message.RecipientType.TO)[0].toString());

    // User needs to be registered
    assertEquals(Status.OKAY, userResult.getStatus());
    assertTrue(userResult.isSuccess());

    User registeredUser = userResult.getUser();
    assertEquals(email, registeredUser.getEmail());
    assertFalse(registeredUser.getIsActivated());
    assertFalse(registeredUser.getIsLoggedIn());

    // Try to register the same email again
    userResult =
        webResource
            .type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .post(UserResult.class, requestHash);

    // Should be failed with email already registered exception
    assertEquals(Status.EMAIL_ALREADY_REGISTERED, userResult.getStatus());
    assertFalse(userResult.isSuccess());

    assertNull(userResult.getUser());
  }
コード例 #12
0
ファイル: AspirinInternal.java プロジェクト: miltonio/aspirin
  public static Collection<InternetAddress> extractRecipients(MimeMessage message)
      throws MessagingException {
    Collection<InternetAddress> recipients = new ArrayList<InternetAddress>();

    Address[] addresses;
    Message.RecipientType[] types =
        new Message.RecipientType[] {RecipientType.TO, RecipientType.CC, RecipientType.BCC};
    for (Message.RecipientType recType : types) {
      addresses = message.getRecipients(recType);
      if (addresses != null) {
        for (Address addr : addresses) {
          try {
            recipients.add((InternetAddress) addr);
          } catch (Exception e) {
            log.warn("Recipient parsing failed.", e);
          }
        }
      }
    }
    return recipients;
  }
コード例 #13
0
  @Test
  public void shouldInviteUser() throws Exception {
    String fromEmail = "*****@*****.**";
    String toEmail = "*****@*****.**";

    Client client = createClient();
    WebResource webResource = client.resource(ringringServerApi.getUrl() + "/user");

    // Create request hash with email address
    HashMap<String, String> requestHash = new HashMap<String, String>();
    requestHash.put("email", fromEmail);

    // First email registration
    UserResult userResult =
        webResource
            .type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .post(UserResult.class, requestHash);
    assertEquals(Status.OKAY, userResult.getStatus());
    assertNotNull(userResult.getUser());

    // Invit an other user
    HashMap<String, String> inviteRequestHash = new HashMap<String, String>();
    inviteRequestHash.put("from_email", fromEmail);
    inviteRequestHash.put("to_email", toEmail);

    webResource = client.resource(ringringServerApi.getUrl() + "/user/" + toEmail + "/invite");
    StatusResult statusResult =
        webResource
            .type(MediaType.APPLICATION_JSON_TYPE)
            .accept(MediaType.APPLICATION_JSON_TYPE)
            .post(StatusResult.class, inviteRequestHash);
    assertEquals(Status.OKAY, statusResult.getStatus());

    // Check if email sent to the user
    MimeMessage message = getLastMail().getMimeMessage();
    assertEquals(configManager.getSmtpFrom(), message.getFrom()[0].toString());
    assertEquals(toEmail, message.getRecipients(Message.RecipientType.TO)[0].toString());
  }
コード例 #14
0
ファイル: MailSender.java プロジェクト: GabrielGhe/MailClient
  /**
   * Sent the message to a plain SMTP server like Waldo
   *
   * @param mmd the MailMessageData to send
   * @return success or failure
   */
  private boolean smtpSend(Mail mail) {
    boolean retVal = true;
    Session session = null;

    try {
      // Create a properties object
      Properties smtpProps = new Properties();

      // Add mail configuration to the properties
      smtpProps.put("mail.transport.protocol", "smtp");

      smtpProps.put("mail.smtp.host", mailConfig.getUrlSmtp());
      smtpProps.put("mail.smtp.port", mailConfig.getPortSmtp());

      if (mailConfig.isSMTPAuth()) {
        Authenticator auth = new SMTPAuthenticator();
        session = Session.getInstance(smtpProps, auth);
      } else session = Session.getDefaultInstance(smtpProps, null);

      // Display the conversation between the client and server
      if (DEBUG) session.setDebug(true);

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

      // Set the single from field
      msg.setFrom(new InternetAddress(mailConfig.getUserEmail()));

      // Set the To, CC, and BCC from their ArrayLists
      for (String emailAddress : mail.getToRecipients())
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress, false));

      if (mail.getCcRecipients() != null)
        for (String emailAddress : mail.getCcRecipients())
          if (!emailAddress.equals(""))
            msg.addRecipient(Message.RecipientType.CC, new InternetAddress(emailAddress, false));

      if (mail.getBccRecipients() != null)
        for (String emailAddress : mail.getBccRecipients())
          if (!emailAddress.equals(""))
            msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(emailAddress, false));

      // Set the subject
      msg.setSubject(mail.getSubject());

      // Set the message body
      msg.setText(mail.getContent());

      // Set some other header information
      msg.setHeader("X-Mailer", "Comp Sci Tech Mailer");
      msg.setSentDate(new Date());

      if (mailConfig.isSMTPAuth()) {
        Transport transport = session.getTransport();

        transport.connect();
        transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
        transport.close();
      } else Transport.send(msg);

    } catch (NoSuchProviderException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is no server at the SMTP address.",
          "SMTP-NoSuchProviderException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is no server at the SMTP address.", e);
      retVal = false;
    } catch (AddressException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is an error in a recipient's address.",
          "SMTP-AddressException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is an error in a recipient's address.", e);
      retVal = false;
    } catch (MessagingException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There is a problem with the message.",
          "SMTP-MessagingException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There is a problem with the message.", e);
      retVal = false;
    } catch (Exception e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null,
          "There has been an unknown error.",
          "SMTP-UnknownException",
          JOptionPane.ERROR_MESSAGE);
      logger.log(Level.WARNING, "There has been an unknown error.", e);
      retVal = false;
    }
    return retVal;
  }
コード例 #15
0
ファイル: Emailer.java プロジェクト: baojie1985/MNTG
  public static void sendEmail(String email, String id)
      throws MessagingException, UnsupportedEncodingException {

    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", SMTP_HOST_NAME);
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("Traffic Generation Request #" + id + " has received");

    message.setContent(
        "Hi Sir/Madam, \n\n Your traffic generation request #"
            + id
            + " has been received by DMLab@UMN. \n You will be notified via email "
            + email
            + " , when we finish our processing.\n\n Please be patient. If you have any inquries, please send email to [email protected]. \n\n Thanks, \n DMLab@UMN",
        "text/plain");

    InternetAddress[] mntgAddress = new InternetAddress[1];
    mntgAddress[0] =
        new InternetAddress(
            "*****@*****.**",
            "Minnesota Traffic Generator"); // here we set our email alias and the desired display
    // name
    InternetAddress customer_email = new InternetAddress(email); // customer email

    message.addRecipient(Message.RecipientType.TO, customer_email);

    message.addRecipients(Message.RecipientType.CC, mntgAddress);
    message.addRecipients(Message.RecipientType.BCC, mntgAddress);

    message.setFrom(mntgAddress[0]);
    message.setReplyTo(mntgAddress);
    message.setSender(mntgAddress[0]);

    transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

    Address[] recipientsTo = message.getRecipients(Message.RecipientType.TO);
    Address[] recipientsCC = message.getRecipients(Message.RecipientType.CC);
    Address[] recipientsBCC = message.getRecipients(Message.RecipientType.BCC);

    Address[] allRecipients =
        new Address[recipientsTo.length + recipientsCC.length + recipientsBCC.length];
    int allIndex = 0;
    for (int i = 0; i < recipientsTo.length; ++i, ++allIndex) {
      allRecipients[allIndex] = recipientsTo[i];
    }
    for (int i = 0; i < recipientsCC.length; ++i, ++allIndex) {
      allRecipients[allIndex] = recipientsCC[i];
    }
    for (int i = 0; i < recipientsBCC.length; ++i, ++allIndex) {
      allRecipients[allIndex] = recipientsBCC[i];
    }

    transport.sendMessage(message, allRecipients);

    transport.close();

    //  InternetAddress notifyAddress = new InternetAddress("*****@*****.**", "Admin MailList");
    // //here we set our email alias and the desired display name
    // sendEmail(mntgAddress[0], notifyAddress,                "Traffic request #" + id + " has just
    // been submitted by user " + email + ".", email);

    /*
     * InternetAddress notifyAddress3 = new
     * InternetAddress("*****@*****.**", "Mohamed Mokbel"); //here we set
     * our email alias and the desired display name
     * sendEmail(mntgAddress[0], notifyAddress3, "Traffic request #" + id +
     * " has just been submitted by user " + email + ".", email);
     *
     */

  }
コード例 #16
0
  public static void readTrainingMail(String fileNameWithPath) {
    InputStream is;

    try {
      is = new FileInputStream(fileNameWithPath);

      Properties props = System.getProperties();
      props.put("mail.host", "stmp.gmail.com");
      props.put("mail.transport.protocol", "stmp");
      Session mailSession = Session.getDefaultInstance(props, null);

      MimeMessage message = new MimeMessage(mailSession, is);

      if (message.getSubject() != null) {
        System.out.println("subject ---> " + message.getSubject());
      }

      if (message.getFrom() != null) {
        System.out.println(message.getFrom()[0].toString());
      }

      /**
       * The Message.RecipientType is divided into TO , the primary recipients -- CC ,carbon copy
       * recipients -- 抄送 BCC, blind carbon copy recipients-- 发送邮件副本,又不想让原始接收人知道,密抄送
       */
      if (message.getRecipients(MimeMessage.RecipientType.CC) != null) {
        System.out.println("CC : found " + message.getRecipients(Message.RecipientType.CC));
      }

      if (message.getRecipients(Message.RecipientType.BCC) != null) {
        System.out.println("BCc : Found " + message.getRecipients(Message.RecipientType.BCC));
      }

      if (message.getRecipients(Message.RecipientType.TO) != null) {
        System.out.println("To Found " + message.getRecipients(Message.RecipientType.TO));
        Address[] AddressList = message.getRecipients(Message.RecipientType.TO);

        for (Address internetAddress : AddressList) {
          InternetAddress addr = (InternetAddress) internetAddress;
          System.out.println(addr.getAddress());
        }
      }

      if (message.getSentDate() != null) {
        System.out.println("message Date : " + message.getSentDate());
      }

      System.out.println("here is the email 's content type name");
      System.out.println(message.getContentType());
      System.out.println("here is the email content ");
      System.out.println(message.getContent());

      if (message.getContentType().startsWith("multipart")) {
        Multipart multiPart = (Multipart) message.getContent();

        for (int x = 0; x < multiPart.getCount(); x++) {
          BodyPart bodyPart = multiPart.getBodyPart(x);
          String disposition = bodyPart.getDisposition();

          if (disposition != null) {
            String content = html2text((String) bodyPart.getContent()).trim();

            System.out.println("Content : " + content);
            System.out.println("disposition " + disposition);
          }

          System.out.println("is email contains disposition ? ");
          if (disposition != null && disposition.equals(BodyPart.ATTACHMENT))
            System.out.println("yes");
          else System.out.println("no");
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #17
0
  public void testDelayedEmailNotificationOnDeadline() throws Exception {
    Map vars = new HashMap();
    vars.put("users", users);
    vars.put("groups", groups);
    vars.put("now", new Date());

    DefaultEscalatedDeadlineHandler notificationHandler =
        new DefaultEscalatedDeadlineHandler(getConf());
    WorkItemManager manager = new DefaultWorkItemManager(null);
    notificationHandler.setManager(manager);

    MockUserInfo userInfo = new MockUserInfo();
    userInfo.getEmails().put(users.get("tony"), emailAddressTony);
    userInfo.getEmails().put(users.get("darth"), emailAddressDarth);

    userInfo.getLanguages().put(users.get("tony"), "en-UK");
    userInfo.getLanguages().put(users.get("darth"), "en-UK");
    notificationHandler.setUserInfo(userInfo);

    taskService.setEscalatedDeadlineHandler(notificationHandler);

    Reader reader =
        new InputStreamReader(
            getClass().getResourceAsStream(MvelFilePath.DeadlineWithNotification));
    Task task = (Task) eval(reader, vars);

    BlockingAddTaskResponseHandler addTaskResponseHandler = new BlockingAddTaskResponseHandler();
    client.addTask(task, null, addTaskResponseHandler);
    long taskId = addTaskResponseHandler.getTaskId();

    Content content = new Content();
    content.setContent("['subject' : 'My Subject', 'body' : 'My Body']".getBytes());
    BlockingSetContentResponseHandler setContentResponseHandler =
        new BlockingSetContentResponseHandler();
    client.setDocumentContent(taskId, content, setContentResponseHandler);
    long contentId = setContentResponseHandler.getContentId();
    BlockingGetContentResponseHandler getResponseHandler = new BlockingGetContentResponseHandler();
    client.getContent(contentId, getResponseHandler);
    content = getResponseHandler.getContent();
    assertEquals(
        "['subject' : 'My Subject', 'body' : 'My Body']", new String(content.getContent()));

    // emails should not be set yet
    assertEquals(0, getWiser().getMessages().size());
    Thread.sleep(100);

    // nor yet
    assertEquals(0, getWiser().getMessages().size());

    long time = 0;
    while (getWiser().getMessages().size() != 2 && time < 15000) {
      Thread.sleep(500);
      time += 500;
    }

    // 1 email with two recipients should now exist
    assertEquals(2, getWiser().getMessages().size());

    List<String> list = new ArrayList<String>(2);
    list.add(getWiser().getMessages().get(0).getEnvelopeReceiver());
    list.add(getWiser().getMessages().get(1).getEnvelopeReceiver());

    assertTrue(list.contains(emailAddressTony));
    assertTrue(list.contains(emailAddressDarth));

    MimeMessage msg = ((WiserMessage) getWiser().getMessages().get(0)).getMimeMessage();
    assertEquals("My Body", msg.getContent());
    assertEquals("My Subject", msg.getSubject());
    assertEquals("*****@*****.**", ((InternetAddress) msg.getFrom()[0]).getAddress());
    assertEquals("*****@*****.**", ((InternetAddress) msg.getReplyTo()[0]).getAddress());
    boolean tonyMatched = false;
    boolean darthMatched = false;
    for (int i = 0; i < msg.getRecipients(RecipientType.TO).length; ++i) {
      String emailAddress = ((InternetAddress) msg.getRecipients(RecipientType.TO)[i]).getAddress();
      if ("*****@*****.**".equals(emailAddress)) {
        tonyMatched = true;
      } else if ("*****@*****.**".equals(emailAddress)) {
        darthMatched = true;
      }
    }
    assertTrue("Could not find tony in recipients list.", tonyMatched);
    assertTrue("Could not find darth in recipients list.", darthMatched);
  }