Пример #1
0
 @Override
 public void send() throws MessagingException, UnsupportedEncodingException {
   long t0 = System.currentTimeMillis();
   try {
     if (iMail.getFrom() == null || iMail.getFrom().length == 0)
       setFrom(
           ApplicationProperty.EmailSenderAddress.value(),
           ApplicationProperty.EmailSenderName.value());
     if (iMail.getReplyTo() == null || iMail.getReplyTo().length == 0)
       setReplyTo(
           ApplicationProperty.EmailReplyToAddress.value(),
           ApplicationProperty.EmailReplyToName.value());
     iMail.setSentDate(new Date());
     iMail.setContent(iBody);
     iMail.saveChanges();
     Transport.send(iMail);
   } finally {
     long t = System.currentTimeMillis() - t0;
     if (t > 30000)
       sLog.warn(
           "It took "
               + new DecimalFormat("0.00").format(t / 1000.0)
               + " seconds to send an email.");
     else if (t > 5000)
       sLog.info(
           "It took "
               + new DecimalFormat("0.00").format(t / 1000.0)
               + " seconds to send an email.");
   }
 }
Пример #2
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop, null);
    SendMail sm = new SendMail();
    String br = "\n";

    try {
      // 受信メールを取得
      MimeMessage recMsg = new MimeMessage(session, req.getInputStream());

      DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
      String sentDate = df.format(recMsg.getSentDate());
      String from = recMsg.getFrom().toString();
      String subject = recMsg.getSubject();
      String content = this.getText(recMsg.getContent());

      String msgBody = "";
      msgBody += "sent at : " + sentDate + br;
      msgBody += "from : " + from + br;
      msgBody += "subject : " + subject + br;
      msgBody += "-----------content----------" + br + content;
      sm.send("*****@*****.**", "", "sutekitest転送", msgBody);
    } catch (MessagingException e) {
      sm.send("*****@*****.**", "", "sutekitestメール受信エラー", e.getMessage() + br + e.getCause());
    }
  }
Пример #3
0
  // -- 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);
  }
 /**
  * Process specified MIME type of MimeMessage to get attachments and save them to disk.
  *
  * @param mime
  * @return
  * @throws MessagingException
  * @throws IOException
  * @throws CMSException
  * @throws OperatorCreationException
  * @throws CertificateException
  */
 protected String processMessage(MimeMessage mime)
     throws MessagingException, IOException, CMSException, OperatorCreationException,
         CertificateException {
   String attachList = null;
   if (mime.isMimeType("text/html")
       || mime.isMimeType("text/plain")
       || mime.isMimeType("multipart/mixed")) {
     // simple mail with attachment
     attachList = this.processAttachmentsOfSimpleMail(mime);
   } else if (mime.isMimeType("multipart/signed")) {
     // signed mail with attachment
     attachList = this.processAttachmentsOfSignedMail(mime);
   } else if (mime.isMimeType("application/pkcs7-mime")
       || mime.isMimeType("application/x-pkcs7-mime")) {
     String e = "It's an encrypted mail. Can not handle the Message receiving from Mail Server.";
     LOG.error(e);
     throw new MessagingException(e);
   } else {
     String e =
         "Unknown MIME Type | Message Content Type: "
             + mime.getContentType()
             + ", Message Subject: "
             + mime.getSubject()
             + ", Message Send Date: "
             + mime.getSentDate()
             + ", Message From: "
             + mime.getFrom().toString();
     LOG.error(e);
     throw new MessagingException(e);
   }
   return attachList;
 }
 public Address[] getFrom() {
   MimeMessage message = getMessage();
   try {
     return message.getFrom();
   } catch (MessagingException e) {
     Debug.logError(e, module);
     return null;
   }
 }
  @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());
  }
Пример #7
0
  public EmailMessage parseToBetterFormat(MimeMessage m) {
    try {
      EmailMessage email = new EmailMessage();
      Address[] senders = m.getFrom();
      if ((senders == null) || senders.length != 1) {
        LOG.severe("ignoring incoming email with null or multiple from's: " + senders);
        return null;
      }
      email.from = new InternetAddress(senders[0].toString());

      Address[] recipients = m.getAllRecipients();
      if (recipients == null) {
        LOG.severe("ignoring incoming email with null recipient list from sender: " + email.from);
        return null;
      }
      email.to = Lists.newArrayList();

      for (Address a : recipients) {
        email.to.add(new InternetAddress(a.toString()));
      }

      email.subject = m.getSubject();

      String contentType = m.getContentType();
      if (!contentType.startsWith("text/plain;") && !contentType.startsWith("text/html;")) {
        LOG.log(Level.WARNING, "ignoring message with unrecognized content type" + contentType);
        return null;
      }
      try {
        // This is stupid, but I've seen both ByteArrayInputStream and String,
        // and the interface doesn't specify one.
        Object o = m.getContent();
        if (o instanceof String) {
          email.body = (String) o;
        } else if (o instanceof ByteArrayInputStream) {
          ByteArrayInputStream stream = (ByteArrayInputStream) o;
          byte[] bytes = new byte[stream.available()];
          stream.read(bytes);
          email.body = new String(bytes);
        }
      } catch (IOException e) {
        LOG.log(
            Level.SEVERE,
            "Caught exception while trying to read content of email from " + email.from,
            e);
        return null;
      }

      return email;
    } catch (MessagingException e) {
      LOG.log(Level.SEVERE, "Couldn't parse incoming email", e);
      return null;
    }
  }
  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
  public void sendEmail() throws MessagingException {
    if (msg.getFrom() == null)
      msg.setFrom(new InternetAddress("*****@*****.**"));
    msg.setHeader("X-mailer", "msgsend");
    msg.setRecipients(Message.RecipientType.TO, (Address[]) toList.toArray(new Address[0]));
    msg.setRecipients(Message.RecipientType.CC, (Address[]) ccList.toArray(new Address[0]));
    msg.setRecipients(Message.RecipientType.BCC, (Address[]) bccList.toArray(new Address[0]));
    msg.setSentDate(new Date());

    if (!toList.isEmpty()) Transport.send(msg);
  }
Пример #10
0
 public static Map<String, Object> mcaTest(DispatchContext dctx, Map<String, ?> context) {
   MimeMessageWrapper wrapper = (MimeMessageWrapper) context.get("messageWrapper");
   MimeMessage message = wrapper.getMessage();
   try {
     if (message.getAllRecipients() != null) {
       Debug.log("To: " + UtilMisc.toListArray(message.getAllRecipients()), module);
     }
     if (message.getFrom() != null) {
       Debug.log("From: " + UtilMisc.toListArray(message.getFrom()), module);
     }
     Debug.log("Subject: " + message.getSubject(), module);
     if (message.getSentDate() != null) {
       Debug.log("Sent: " + message.getSentDate().toString(), module);
     }
     if (message.getReceivedDate() != null) {
       Debug.log("Received: " + message.getReceivedDate().toString(), module);
     }
   } catch (Exception e) {
     Debug.logError(e, module);
   }
   return ServiceUtil.returnSuccess();
 }
Пример #11
0
  @Test
  public void sendSimpleMail() throws MessagingException, InterruptedException, IOException {
    simpleMailService.sendNotificationMail("calvin");

    greenMail.waitForIncomingEmail(2000, 1);

    MimeMessage[] messages = greenMail.getReceivedMessages();
    MimeMessage message = messages[messages.length - 1];

    assertEquals("*****@*****.**", message.getFrom()[0].toString());
    assertEquals("用户修改通知", message.getSubject());
    // text格式内容
    System.out.println(message.getContent());
    assertTrue(((String) message.getContent()).contains("被修改"));
  }
  @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());
  }
  @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());
  }
Пример #14
0
 private void logMail(MimeMessage msg) {
   try {
     String to = "";
     Address[] toAddresses = msg.getAllRecipients();
     if (toAddresses.length == 1) {
       to = toAddresses[0].getType();
     } else if (toAddresses.length > 1) {
       to = toAddresses[0].getType() + " and  #" + (msg.getAllRecipients().length - 1) + " other";
     } else {
       to = "NO-TO-ADDRESS";
     }
     log.info("Mail Test-Mode: Would send mail to=" + to + " with subject=" + msg.getSubject());
     if (log.isDebugEnabled()) {
       log.debug("Mail Test-Mode: from=" + msg.getFrom()[0]);
       log.debug("Mail Test-Mode: content=" + msg.getContent() + "'");
     }
   } catch (Exception e) {
     log.warn("Could not extract log-info from mime-message, ", e);
   }
 }
Пример #15
0
 /* (non-Javadoc)
  * @see uk.ac.hpcx.model.helpdesk.MessageProvider#getSender()
  */
 public final String getSender() {
   try {
     MimeMessage m = getMessage();
     if (m != null) {
       Address from[] = m.getFrom();
       StringBuilder sb = new StringBuilder();
       if (from != null) {
         for (int i = 0; i < from.length; i++) {
           if (i > 0) {
             sb.append(", ");
           }
           sb.append(from[i]);
         }
       }
       return sb.toString();
     }
   } catch (Exception e) {
     getContext().error(e, "Error getting sender");
   }
   return "Unknown";
 }
  @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());
  }
  /**
   * 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);
  }
Пример #18
0
  @Test
  public void sendMimeMail() throws InterruptedException, MessagingException, IOException {
    mimeMailService.sendNotificationMail("calvin");

    greenMail.waitForIncomingEmail(2000, 1);
    MimeMessage[] messages = greenMail.getReceivedMessages();
    MimeMessage message = messages[messages.length - 1];

    assertEquals("*****@*****.**", message.getFrom()[0].toString());
    assertEquals("用户修改通知", message.getSubject());

    MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();

    assertEquals(2, mimeMultipart.getCount());

    // Html格式的主邮件
    String mainPartText = getMainPartText(mimeMultipart.getBodyPart(0));
    System.out.println(mainPartText);
    assertTrue(mainPartText.contains("<h1>用户calvin被修改.</h1>"));

    // 附件
    assertEquals(
        "Hello,i am a attachment.", GreenMailUtil.getBody(mimeMultipart.getBodyPart(1)).trim());
  }
Пример #19
0
  private void handleMail(
      HttpServletRequest request, HttpServletResponse response, BlogAuthor blogAuthor)
      throws IOException, ServletException, EntityNotFoundException, MessagingException,
          HttpException {
    DS ds = DS.get();
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session, request.getInputStream());
    String messageId = getMessageId(message);
    String contentType = message.getContentType();

    if (messageId == null) {
      log("messageID missing");
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }
    log("Message-ID=" + messageId);
    // TODO authorization
    if (handleSpot(message)) {
      return;
    }
    InternetAddress sender = (InternetAddress) message.getSender();
    log("sender=" + sender);
    if (sender == null) {
      Address[] from = message.getFrom();
      if (from != null && from.length != 0) {
        sender = (InternetAddress) from[0];
      }
    }
    if (sender == null) {
      log("Sender missing");
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }
    Email senderEmail = new Email(sender.getAddress());
    Settings settings = ds.getSettingsFor(senderEmail);
    if (settings == null) {
      log(senderEmail.getEmail() + " not allowed to send blogs");
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
      return;
    }
    String[] ripperDate = message.getHeader(BlogRipper + "Date");
    boolean ripping = ripperDate != null && ripperDate.length > 0;
    Object content = message.getContent();
    if (content instanceof Multipart) {
      Multipart multipart = (Multipart) message.getContent();
      List<BodyPart> bodyPartList = findParts(multipart);
      try {
        Entity blog = null;
        String htmlBody = getHtmlBody(bodyPartList);
        if (htmlBody != null && htmlBody.length() > 10) {
          boolean publishImmediately = settings.isPublishImmediately();
          blog = updateBlog(messageId, message, htmlBody, publishImmediately, senderEmail);
          if (!ripping) {
            if (blog != null) {
              sendMail(request, blogAuthor, blog, settings);
            }
          } else {
            log("not sending email because ripping");
          }
        } else {
          log("no html body");
        }
        List<Future<HTTPResponse>> futureList = new ArrayList<Future<HTTPResponse>>();
        for (BodyPart bodyPart : bodyPartList) {
          Collection<Future<HTTPResponse>> futures =
              handleBodyPart(request, blog, bodyPart, settings);
          if (futures != null) {
            futureList.addAll(futures);
          }
        }
        long remainingMillis = ApiProxy.getCurrentEnvironment().getRemainingMillis();
        log("remainingMillis=" + remainingMillis);
        for (Future<HTTPResponse> res : futureList) {
          try {
            HTTPResponse hr = res.get();
            log("code=" + hr.getResponseCode());
            if (hr.getResponseCode() != HttpServletResponse.SC_OK) {
              throw new ServletException("blob upload failed code=" + hr.getResponseCode());
            }
          } catch (InterruptedException ex) {
            throw new IOException(ex);
          } catch (ExecutionException ex) {
            throw new IOException(ex);
          }
        }
      } catch (MessagingException ex) {
        throw new IOException(ex);
      }
    } else {
      if (content instanceof String) {
        String bodyPart = (String) content;
        if (contentType.startsWith("text/plain")) {
          bodyPart = textPlainToHtml(bodyPart);
        }
        boolean publishImmediately = settings.isPublishImmediately();
        Entity blog = updateBlog(messageId, message, bodyPart, publishImmediately, senderEmail);
        if (blog != null) {
          sendMail(request, blogAuthor, blog, settings);
        }
      } else {
        log("body not MultiPart of String");
      }
    }
  }
Пример #20
0
    public void run() {
      Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

      if (!circuitBreaker.isOn()) return; // Don't try - circuit breaker is off

      boolean expunge = config.configuration().deleteMailOnInboxClose().get();
      if (config.configuration().debug().get()) {
        logger.info("Checking email");
        logger.info("Delete mail on close - " + expunge);
      }

      Session session = javax.mail.Session.getInstance(props, authenticator);
      session.setDebug(config.configuration().debug().get());

      Usecase usecase = newUsecase("Receive Mail");
      UnitOfWork uow = null;
      Store store = null;
      Folder inbox = null;
      Folder archive = null;
      boolean archiveExists = false;
      List<Message> copyToArchive = new ArrayList<Message>();
      MimeMessage internalMessage = null;

      try {
        store = session.getStore(url);
        store.connect();

        inbox = store.getFolder("INBOX");
        inbox.open(Folder.READ_WRITE);

        javax.mail.Message[] messages = inbox.getMessages();
        FetchProfile fp = new FetchProfile();
        //            fp.add( "In-Reply-To" );
        inbox.fetch(messages, fp);

        // check if the archive folder is configured and exists
        if (!Strings.empty(config.configuration().archiveFolder().get())
            && config.configuration().protocol().get().startsWith("imap")) {
          archive = store.getFolder(config.configuration().archiveFolder().get());

          // if not exists - create
          if (!archive.exists()) {
            archive.create(Folder.HOLDS_MESSAGES);
            archiveExists = true;
          } else {
            archiveExists = true;
          }

          archive.open(Folder.READ_WRITE);
        }

        for (javax.mail.Message message : messages) {
          int tries = 0;
          while (tries < 3) {
            uow = module.unitOfWorkFactory().newUnitOfWork(usecase);

            ValueBuilder<EmailValue> builder =
                module.valueBuilderFactory().newValueBuilder(EmailValue.class);

            try {
              // Force a complete fetch of the message by cloning it to a internal MimeMessage
              // to avoid "javax.mail.MessagingException: Unable to load BODYSTRUCTURE" problems
              // f.ex. experienced if the message contains a windows .eml file as attachment!

              // Beware that all flag and folder operations have to be made on the original message
              // and not on the internal one!!
              internalMessage = new MimeMessage((MimeMessage) message);

              Object content = internalMessage.getContent();

              // Get email fields
              builder
                  .prototype()
                  .from()
                  .set(((InternetAddress) internalMessage.getFrom()[0]).getAddress());
              builder
                  .prototype()
                  .fromName()
                  .set(((InternetAddress) internalMessage.getFrom()[0]).getPersonal());
              builder
                  .prototype()
                  .subject()
                  .set(internalMessage.getSubject() == null ? "" : internalMessage.getSubject());

              // Get headers
              for (Header header :
                  Iterables.iterable((Enumeration<Header>) internalMessage.getAllHeaders())) {
                builder.prototype().headers().get().put(header.getName(), header.getValue());
              }

              // Get all recipients in order - TO, CC, BCC
              // and provide it to the toaddress method to pick the first possible valid adress
              builder
                  .prototype()
                  .to()
                  .set(
                      toaddress(
                          internalMessage.getAllRecipients(),
                          builder.prototype().headers().get().get("References")));

              builder.prototype().messageId().set(internalMessage.getHeader("Message-ID")[0]);

              // Get body and attachments
              String body = "";
              // set content initially so it never can become null
              builder.prototype().content().set(body);

              if (content instanceof String) {
                body = content.toString();
                builder.prototype().content().set(body);
                String contentTypeString = cleanContentType(internalMessage.getContentType());
                builder.prototype().contentType().set(contentTypeString);
                if (Translator.HTML.equalsIgnoreCase(contentTypeString)) {
                  builder.prototype().contentHtml().set(body);
                }

              } else if (content instanceof Multipart) {
                handleMultipart((Multipart) content, internalMessage, builder);
              } else if (content instanceof InputStream) {
                content = new MimeMessage(session, (InputStream) content).getContent();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                Inputs.byteBuffer((InputStream) content, 4096).transferTo(Outputs.byteBuffer(baos));

                String data = new String(baos.toByteArray(), "UTF-8");
                // Unknown content type - abort
                // and create failure case
                String subj = "Unkonwn content type: " + internalMessage.getSubject();
                builder
                    .prototype()
                    .subject()
                    .set(subj.length() > 50 ? subj.substring(0, 50) : subj);
                builder.prototype().content().set(body);
                builder.prototype().contentType().set(internalMessage.getContentType());
                systemDefaults.createCaseOnEmailFailure(builder.newInstance());
                copyToArchive.add(message);
                if (expunge) message.setFlag(Flags.Flag.DELETED, true);

                uow.discard();
                tries = 3;
                continue;
              } else {
                // Unknown content type - abort
                // and create failure case
                String subj = "Unkonwn content type: " + internalMessage.getSubject();
                builder
                    .prototype()
                    .subject()
                    .set(subj.length() > 50 ? subj.substring(0, 50) : subj);
                builder.prototype().content().set(body);
                builder.prototype().contentType().set(internalMessage.getContentType());
                systemDefaults.createCaseOnEmailFailure(builder.newInstance());
                copyToArchive.add(message);
                if (expunge) message.setFlag(Flags.Flag.DELETED, true);

                uow.discard();
                logger.error(
                    "Could not parse emails: unknown content type " + content.getClass().getName());
                tries = 3;
                continue;
              }

              // make sure mail content fit's into statistic database - truncate on 65.500
              // characters.
              if (builder.prototype().content().get().length() > 65000) {
                builder
                    .prototype()
                    .content()
                    .set(builder.prototype().content().get().substring(0, 65000));
              }

              // try to reveal if it is a smpt error we are looking at
              // X-Failed-Recipients is returned by Gmail
              // X-FC-MachineGenerated is returned by FirstClass
              // Exchange is following RFC 6522 -  The Multipart/Report Media Type for
              // the Reporting of Mail System Administrative Messages
              boolean isSmtpErrorReport =
                  !Strings.empty(builder.prototype().headers().get().get("X-Failed-Recipients"))
                      || (!Strings.empty(
                              builder.prototype().headers().get().get("X-FC-MachineGenerated"))
                          && "true"
                              .equals(
                                  builder.prototype().headers().get().get("X-FC-MachineGenerated")))
                      || !Strings.empty(
                          new ContentType(builder.prototype().headers().get().get("Content-Type"))
                              .getParameter("report-type"));

              if (isSmtpErrorReport) {
                // This is a mail bounce due to SMTP error - create support case.
                String subj = "Undeliverable mail: " + builder.prototype().subject().get();

                builder
                    .prototype()
                    .subject()
                    .set(subj.length() > 50 ? subj.substring(0, 50) : subj);
                systemDefaults.createCaseOnEmailFailure(builder.newInstance());
                copyToArchive.add(message);
                if (expunge) message.setFlag(Flags.Flag.DELETED, true);

                uow.discard();
                logger.error("Received a mail bounce reply: " + body);
                tries = 3;
                continue;
              }

              if (builder.prototype().to().get().equals("n/a")) {
                // This is a mail has no to address - create support case.

                String subj = "No TO address: " + builder.prototype().subject().get();

                builder
                    .prototype()
                    .subject()
                    .set(subj.length() > 50 ? subj.substring(0, 50) : subj);
                systemDefaults.createCaseOnEmailFailure(builder.newInstance());
                copyToArchive.add(message);
                if (expunge) message.setFlag(Flags.Flag.DELETED, true);

                uow.discard();
                logger.error("Received a mail without TO address: " + body);
                tries = 3;
                continue;
              }

              mailReceiver.receivedEmail(null, builder.newInstance());

              try {
                logger.debug("This is try " + tries);
                uow.complete();
                tries = 3;
              } catch (ConcurrentEntityModificationException ceme) {
                if (tries < 2) {
                  logger.debug("Encountered ConcurrentEntityModificationException - try again ");
                  // discard uow and try again
                  uow.discard();
                  tries++;
                  continue;

                } else {
                  logger.debug("Rethrowing ConcurrentEntityModification.Exception");
                  tries++;
                  throw ceme;
                }
              }

              copyToArchive.add(message);
              // remove mail on success if expunge is true
              if (expunge) message.setFlag(Flags.Flag.DELETED, true);

            } catch (Throwable e) {
              String subj = "Unknown error: " + internalMessage.getSubject();
              builder.prototype().subject().set(subj.length() > 50 ? subj.substring(0, 50) : subj);

              StringBuilder content = new StringBuilder();
              content.append("Error Message: " + e.getMessage());
              content.append("\n\rStackTrace:\n\r");
              for (StackTraceElement trace : Arrays.asList(e.getStackTrace())) {
                content.append(trace.toString() + "\n\r");
              }

              builder.prototype().content().set(content.toString());
              // since we create the content of the message our self it's ok to set content type
              // always to text/plain
              builder.prototype().contentType().set("text/plain");

              // Make sure to address has some value before vi create a case!!
              if (builder.prototype().to().get() == null) {
                builder.prototype().to().set("n/a");
              }
              systemDefaults.createCaseOnEmailFailure(builder.newInstance());
              copyToArchive.add(message);
              if (expunge) message.setFlag(Flags.Flag.DELETED, true);

              uow.discard();
              logger.error("Could not parse emails", e);
              tries = 3;
            }
          }
        }

        // copy message to archive if archive exists
        if (archiveExists) {
          inbox.copyMessages(copyToArchive.toArray(new Message[0]), archive);
          archive.close(false);
        }

        inbox.close(config.configuration().deleteMailOnInboxClose().get());

        store.close();

        if (config.configuration().debug().get()) {
          logger.info("Checked email");
        }

        circuitBreaker.success();
      } catch (Throwable e) {
        logger.error("Error in mail receiver: ", e);
        circuitBreaker.throwable(e);

        try {
          if (inbox != null && inbox.isOpen()) inbox.close(false);

          if (store != null && store.isConnected()) store.close();
        } catch (Throwable e1) {
          logger.error("Could not close inbox", e1);
        }
      }
    }
Пример #21
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);
  }
  public static List<String> getText(BytesWritable value, Boolean tokenizep)
      throws InterruptedException {
    Session s = Session.getDefaultInstance(new Properties());
    InputStream is = new ByteArrayInputStream(value.getBytes());
    List<String> out = new ArrayList<String>();
    try {
      MimeMessage message = new MimeMessage(s, is);
      message.getAllHeaderLines();

      Analyzer standard_analyzer = new StandardAnalyzer(Version.LUCENE_43);
      Analyzer email_analyzer = new UAX29URLEmailAnalyzer(Version.LUCENE_43);

      Address[] fromAddrs = message.getFrom();
      String fromAddrstr = "";
      if (fromAddrs != null) {
        for (Address addr : fromAddrs) {
          fromAddrstr += (addr.toString() + " ");
        }
      }

      Address[] toAddrs = message.getAllRecipients();
      String toAddrstr = "";
      if (toAddrs != null) {
        for (Address addr : toAddrs) {
          toAddrstr += (addr.toString() + " ");
        }
      }

      String subject = message.getSubject();

      String body = "";
      try {
        Object content = message.getContent();
        // System.err.println(content.getContentType());
        if (content instanceof String) {
          body = (String) content;
        } else if (content instanceof Multipart) {
          Multipart mp = (Multipart) content;
          for (int i = 0; i < mp.getCount(); i++) {
            BodyPart bp = mp.getBodyPart(i);
            // System.err.println(bp.getContentType());
            Object c = bp.getContent();
            if (c instanceof String) {
              body = (String) c;
            }
          }
        }
        // people do really evil things with email, we're not sorting through it all now
      } catch (DecodingException e) {
        System.err.println("DecodingException");
      } catch (UnsupportedEncodingException e) {
        System.err.println("UnsuportedEncodingException");
      } catch (IOException e) {
        System.err.println("IOException");
      }

      if (tokenizep) {
        List<String> fromData = new ArrayList<String>();
        List<String> toData = new ArrayList<String>();
        List<String> subjectData = new ArrayList<String>();
        List<String> bodyData = new ArrayList<String>();

        if (fromAddrstr != null) {
          fromData = tokenizeString(email_analyzer, fromAddrstr);
        }
        if (toAddrstr != null) {
          toData = tokenizeString(email_analyzer, toAddrstr);
        }
        if (subject != null) {
          subjectData = tokenizeString(standard_analyzer, subject);
        }
        if (body != null) {
          bodyData = tokenizeString(standard_analyzer, body);
        }

        out.add("FROM ");
        out.addAll(fromData);

        out.add("TO ");
        out.addAll(toData);

        out.add("SUBJECT ");
        out.addAll(subjectData);

        out.add("BODY ");
        out.addAll(bodyData);
      } else {
        // if not tokenizep, return list with from and subject fields only
        out.add(fromAddrstr);
        out.add(subject);
      }

    } catch (MessagingException e) {
      System.err.println("MessagineException");
    }

    return out;
  }
Пример #23
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();
    }
  }