Example #1
0
  /** Sends Emails to Customers who have not submitted their Bears */
  public static void BearEmailSendMessage(String msgsubject, String msgText, String msgTo) {
    try {
      BearFrom = props.getProperty("BEARFROM");
      // To = props.getProperty("TO");
      SMTPHost = props.getProperty("SMTPHOST");
      Properties mailprops = new Properties();
      mailprops.put("mail.smtp.host", SMTPHost);

      // create some properties and get the default Session
      Session session = Session.getDefaultInstance(mailprops, null);

      // create a message
      Message msg = new MimeMessage(session);

      // set the from
      InternetAddress from = new InternetAddress(BearFrom);
      msg.setFrom(from);
      InternetAddress[] address = InternetAddress.parse(msgTo);
      msg.setRecipients(Message.RecipientType.TO, address);
      msg.setSubject(msgsubject);
      msg.setContent(msgText, "text/plain");
      Transport.send(msg);
    } // end try
    catch (MessagingException mex) {
      USFEnv.getLog().writeCrit("Message not sent", null, null);
    } catch (Exception ex) {
      USFEnv.getLog().writeCrit("Message not sent", null, null);
    }
  } // end BearEmailSendMessage
 /**
  * The address can be a comma-separated sequence of email addresses.
  *
  * @see mail.internet.InternetAddress.parse() for details.
  */
 private InternetAddress[] buildInternetAddressArray(String address)
     throws FrameworkExecutionException {
   // could test for a null or blank String but I'm letting parse just throw an exception
   InternetAddress[] internetAddressArray = null;
   try {
     internetAddressArray = InternetAddress.parse(address);
   } catch (AddressException ae) {
     // do logging here
     throw new FrameworkExecutionException(ae);
   }
   return internetAddressArray;
 }
Example #3
0
  public Object getValueAt(int row, int column) {
    try {
      Message message = getMessage(row);
      switch (column) {
        case 0:
          // Answered?
          return (message.isSet(Flags.Flag.ANSWERED) ? "R" : "");

        case 1:
          // From.
          Address[] addresses = message.getFrom();
          if (addresses == null || addresses.length == 0) {
            return "(No sender)";
          }
          // Given "Personal Name <*****@*****.**>", choose "Personal Name" if it's available, and
          // "*****@*****.**" if not.
          InternetAddress address = (InternetAddress) addresses[0];
          String name = address.getPersonal();
          return (name != null) ? name : address.getAddress();

        case 2:
          // Subject.
          String subject = message.getSubject();
          return (subject != null) ? subject : "(No subject)";

        case 3:
          // Date.
          Date date = message.getReceivedDate();
          return (date != null) ? Mailer.dateToIsoString(date) : "Unknown";

        default:
          return "<no-column-" + column + ">";
      }
    } catch (MessagingException ex) {
      ex.printStackTrace();
      return "<error>";
    }
  }
  public void sendEMailToUser(ICFSecuritySecUserObj toUser, String msgSubject, String msgBody)
      throws IOException, MessagingException, NamingException {

    final String S_ProcName = "sendEMailToUser";

    Properties props = System.getProperties();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFInternet25SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpEmailFrom");
    }

    smtpUsername = (String) ctx.lookup("java:comp/env/CFInternet25SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFInternet25SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFInternet25SmtpPassword");
    }

    Session emailSess =
        Session.getInstance(
            props,
            new Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
              }
            });

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(toUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject((msgSubject != null) ? msgSubject : "No subject");
    msg.setSentDate(new Date());
    msg.setContent(msgBody, "text/html");
    msg.saveChanges();

    Transport.send(msg);
  }
  @RequestMapping(method = RequestMethod.POST)
  public ResponseEntity<String> sendNewPassword(@RequestBody String data)
      throws UnsupportedEncodingException, JSONException {
    JSONObject json = new JSONObject(data);
    String email = (String) (json.get("email"));
    List<User> users = userRepository.findByEmail(email);
    if (users.size() > 0) {
      User user = users.get(0);
      String generatedString = UUID.randomUUID().toString().replaceAll("-", "");
      user.setPassword(generatedString);
      userRepository.save(user);
      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", "smtp.gmail.com");
      props.put("mail.smtp.port", "587");
      Session session =
          Session.getInstance(
              props,
              new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication("perseuscontact", "PERSEUS1992");
                }
              });

      try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("*****@*****.**", "Perseus App"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("New password");
        String text =
            "Hello"
                + user.getName()
                + "!.<\br> Your new password is :<b>"
                + generatedString
                + "</b><br/>You can change the passsword again.";
        message.setContent(text, "text/html; charset=utf-8");
        Transport.send(message);
        System.out.println(
            "Message about new password sent to the user " + user.getEmail() + " - " + email);
      } catch (MessagingException e) {
        System.out.println("Error sending a 'user joined' message.");
        throw new RuntimeException(e);
      }
    }
    return new ResponseEntity<>(email, HttpStatus.CREATED);
  }
  private void doit(String[] argv) {
    String to = null,
        subject = null,
        from = null,
        replyTo = null,
        cc = null,
        bcc = null,
        url = null;
    String mailhost = null;
    String mailer = "MsgSend";
    String protocol = null, host = null, user = null, password = null, record = null;
    String filename = null, msg_text = null, inline_filename = null;
    boolean debug = false;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    int optind;

    for (optind = 0; optind < argv.length; optind++) {
      if (argv[optind].equals("-T")) {
        protocol = argv[++optind];
      } else if (argv[optind].equals("-X")) {
        msg_text = argv[++optind];
      } else if (argv[optind].equals("-H")) {
        host = argv[++optind];
      } else if (argv[optind].equals("-U")) {
        user = argv[++optind];
      } else if (argv[optind].equals("-P")) {
        password = argv[++optind];
      } else if (argv[optind].equals("-M")) {
        mailhost = argv[++optind];
      } else if (argv[optind].equals("-f")) {
        filename = argv[++optind];
      } else if (argv[optind].equals("-i")) {
        inline_filename = argv[++optind];
      } else if (argv[optind].equals("-s")) {
        subject = argv[++optind];
      } else if (argv[optind].equals("-o")) { // originator (from)
        from = argv[++optind];
      } else if (argv[optind].equals("-r")) { // reply-to
        replyTo = argv[++optind];
      } else if (argv[optind].equals("-c")) {
        cc = argv[++optind];
      } else if (argv[optind].equals("-b")) {
        bcc = argv[++optind];
      } else if (argv[optind].equals("-L")) {
        url = argv[++optind];
      } else if (argv[optind].equals("-d")) {
        debug = true;
      } else if (argv[optind].equals("--")) {
        optind++;
        break;
      } else if (argv[optind].startsWith("-")) {
        System.err.println(USAGE_TEXT);
        System.exit(1);
      } else {
        break;
      }
    }

    try {
      if (optind < argv.length) {
        // XXX - concatenate all remaining arguments
        to = argv[optind];
        System.out.println("To: " + to);
      } else {
        System.out.print("To: ");
        System.out.flush();
        to = in.readLine();
      }
      if (subject == null) {
        System.out.print("Subject: ");
        System.out.flush();
        subject = in.readLine();
      } else {
        System.out.println("Subject: " + subject);
      }

      Properties props = System.getProperties();
      // XXX - could use Session.getTransport() and Transport.connect()
      // XXX - assume we're using SMTP
      if (mailhost != null) props.put("mail.smtp.host", mailhost);

      // Get a Session object
      Session session = Session.getInstance(props, null);
      if (debug) session.setDebug(true);

      // construct the message
      Message msg = new MimeMessage(session);

      if (from != null) msg.setFrom(new InternetAddress(from));
      else msg.setFrom();

      if (reply_to_list == null && replyTo != null) {
        reply_to_list = new InternetAddress[1];
        reply_to_list[0] = new InternetAddress(replyTo);
        msg.setReplyTo(reply_to_list);
      } else msg.setReplyTo(reply_to_list);

      if (dis_list == null) {
        dis_list = new InternetAddress[1];
        dis_list[0] = new InternetAddress(to);
      }

      msg.setRecipients(Message.RecipientType.TO, dis_list);
      if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
      if (bcc != null)
        msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));

      // in-line file contents if specified
      if (inline_filename != null) {
        msg_text = readFile(inline_filename);
      }

      // create and fill the first message part
      MimeBodyPart mbp1 = new MimeBodyPart();
      mbp1.setText(msg_text);

      // create the Multipart and add the text part
      Multipart mp = new MimeMultipart();
      mp.addBodyPart(mbp1);

      // create additional message part(s)

      // attach the file or files to the message
      if (filename != null) {
        MimeBodyPart mbp = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(filename);
        mbp.setDataHandler(new DataHandler(fds));
        mbp.setFileName(fds.getName());
        mp.addBodyPart(mbp);
        mbp1.setText(msg_text + "\n\nAttachment: " + filename);
        System.out.println("Added attachment: " + filename);
      }

      if (attachments != null) {
        Iterator i = attachments.iterator();
        StringBuffer list = null;
        while (i.hasNext()) {
          String name = (String) i.next();
          MimeBodyPart mbp = new MimeBodyPart();
          FileDataSource fds = new FileDataSource(name);
          mbp.setDataHandler(new DataHandler(fds));
          mbp.setFileName(fds.getName());
          mp.addBodyPart(mbp);
          if (list == null) {
            list = new StringBuffer(name);
          } else {
            list.append(", " + name);
          }
          System.out.println("Added attachment: " + name);
          mbp1.setText(msg_text + "\nAttachment(s): " + list);
        }
      }

      // add the Multipart to the message
      msg.setContent(mp);

      msg.setSubject(subject);

      // jgfrun collect(in, msg);

      msg.setHeader("X-Mailer", mailer);
      msg.setSentDate(new Date());

      // send the thing off
      Transport.send(msg);

      System.out.println("Mail was sent successfully.");

      // Keep a copy, if requested.
      if (record != null) {

        // Get a Store object
        Store store = null;
        if (url != null) {
          URLName urln = new URLName(url);
          store = session.getStore(urln);
          store.connect();
        } else {
          if (protocol != null) store = session.getStore(protocol);
          else store = session.getStore();

          // Connect
          if (host != null || user != null || password != null) store.connect(host, user, password);
          else store.connect();
        }

        // Get record Folder. Create if it does not exist.
        Folder folder = store.getFolder(record);
        if (folder == null) {
          System.err.println("Can't get record folder.");
          System.exit(1);
        }
        if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES);

        Message[] msgs = new Message[1];
        msgs[0] = msg;
        folder.appendMessages(msgs);

        System.out.println("Mail was recorded successfully.");
      }

    } catch (Exception e) {
      System.err.println("Could not MsgSend.doit");
      e.printStackTrace();
    }
  } // doit
  protected void sendPasswordResetEMail(
      HttpServletRequest request, ICFSecuritySecUserObj resetUser, ICFSecurityClusterObj cluster)
      throws AddressException, MessagingException, NamingException {

    final String S_ProcName = "sendPasswordResetEMail";

    Properties props = System.getProperties();
    String clusterDescription = cluster.getRequiredDescription();

    Context ctx = new InitialContext();

    String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk26SmtpEmailFrom");
    if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk26SmtpEmailFrom");
    }

    smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk26SmtpUsername");
    if ((smtpUsername == null) || (smtpUsername.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk26SmtpUsername");
    }

    smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk26SmtpPassword");
    if ((smtpPassword == null) || (smtpPassword.length() <= 0)) {
      throw CFLib.getDefaultExceptionFactory()
          .newNullArgumentException(
              getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk26SmtpPassword");
    }

    Session emailSess =
        Session.getInstance(
            props,
            new Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(smtpUsername, smtpPassword);
              }
            });

    String thisURI =
        request.getScheme()
            + "://"
            + request.getServerName()
            + ":"
            + request.getServerPort()
            + request.getRequestURI().toString();
    int lastSlash = thisURI.lastIndexOf('/');
    String baseURI = thisURI.substring(0, lastSlash);
    UUID resetUUID = resetUser.getOptionalPasswordResetUuid();

    String msgBody =
        "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n"
            + "<HTML>\n"
            + "<BODY>\n"
            + "<p>\n"
            + "You requested a password reset for "
            + resetUser.getRequiredEMailAddress()
            + " used for accessing "
            + clusterDescription
            + ".\n"
            + "<p>"
            + "Please click on the following link to reset your password:<br>\n"
            + "<A HRef=\""
            + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID="
            + resetUUID.toString()
            + "\">"
            + baseURI
            + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID="
            + resetUUID.toString()
            + "</A>\n"
            + "<p>"
            + "Or click on the following link to cancel the reset request:<br>\n"
            + "<A HRef=\""
            + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID="
            + resetUUID.toString()
            + "\">"
            + baseURI
            + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID="
            + resetUUID.toString()
            + "</A>\n"
            + "</BODY>\n"
            + "</HTML>\n";

    MimeMessage msg = new MimeMessage(emailSess);
    msg.setFrom(new InternetAddress(smtpEmailFrom));
    InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false);
    msg.setRecipient(Message.RecipientType.TO, mailTo[0]);
    msg.setSubject(
        "You requested a password reset for your account with " + clusterDescription + "?");
    msg.setContent(msgBody, "text/html");
    msg.setSentDate(new Date());
    msg.saveChanges();

    Transport.send(msg);
  }