public static void main(String[] args) { // Get the Properties and Create a default session Properties prop = System.getProperties(); prop.setProperty("mail.server.com", "127.0.0.1"); Session session = Session.getDefaultInstance(prop); try { // Set the mail headers MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("*****@*****.**")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress("*****@*****.**")); msg.setSubject("First Mail"); // Create the mime body and attachments MimeBodyPart msgBody = new MimeBodyPart(); msgBody.setContent("Hello World", "text/html"); MimeBodyPart attFile = new MimeBodyPart(); attFile.attachFile("RecvMail.java"); Multipart partMsg = new MimeMultipart(); partMsg.addBodyPart(msgBody); partMsg.addBodyPart(attFile); msg.setContent(partMsg); Transport.send(msg); System.out.println("Message Successfully sent..."); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) { String to = "*****@*****.**"; // change accordingly String from = "*****@*****.**"; // change accordingly String host = "smtp.gmail.com"; // or IP address // Get the session object Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(properties); // compose the message try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Ping"); message.setText("Hello, this is example of sending email "); // Send message Transport.send(message); System.out.println("message sent successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } }
public static void sendMail(String mailMessage) { String to = "*****@*****.**"; String from = "FlotaWeb"; String host = "mail.arabesque.ro"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(properties); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Distributie"); message.setText(mailMessage); Transport.send(message); } catch (MessagingException e) { logger.error(Utils.getStackTrace(e)); } }
public static void main(String[] args) throws MessagingException, IOException { IMAPFolder folder = null; Store store = null; String subject = null; Flag flag = null; try { Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); props.setProperty("mail.imap.host", "imap.googlemail.com"); SimpleAuthenticator authenticator = new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy"); Session session = Session.getDefaultInstance(props, null); // Session session = Session.getDefaultInstance(props, authenticator); store = session.getStore("imaps"); // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy"); // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy"); store.connect("*****@*****.**", "hhy8611hhy"); // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email // account folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account if (!folder.isOpen()) folder.open(Folder.READ_WRITE); Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages(); System.out.println("No of get Messages : " + messages.length); System.out.println("No of Messages : " + folder.getMessageCount()); System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount()); System.out.println("No of New Messages : " + folder.getNewMessageCount()); System.out.println(messages.length); for (int i = 0; i < messages.length; i++) { System.out.println( "*****************************************************************************"); System.out.println("MESSAGE " + (i + 1) + ":"); Message msg = messages[i]; // System.out.println(msg.getMessageNumber()); // Object String; // System.out.println(folder.getUID(msg) subject = msg.getSubject(); System.out.println("Subject: " + subject); System.out.println("From: " + msg.getFrom()[0]); System.out.println("To: " + msg.getAllRecipients()[0]); System.out.println("Date: " + msg.getReceivedDate()); System.out.println("Size: " + msg.getSize()); System.out.println(msg.getFlags()); System.out.println("Body: \n" + msg.getContent()); System.out.println(msg.getContentType()); } } finally { if (folder != null && folder.isOpen()) { folder.close(true); } if (store != null) { store.close(); } } }
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); }
private void SendEmail(String password, String emailTo, String staffNames) { // Recipient's email ID needs to be mentioned. String to = emailTo; // Sender's email ID needs to be mentioned String from = "*****@*****.**"; // Assuming you are sending email from localhost String host = "smtp.upcmail.ie"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("Password Change From Help Manager"); // Now set the actual message message.setText( "Hello " + staffNames + ", \n\n Your new Password is: " + password + ".\n\n Regards \n Help Manager Team"); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } }
private Object receiveMail() throws Exception { Folder folder = null; Store store = null; ConfigurationPropertyManager configManager = ConfigurationPropertyManager.getConfigurationPropertyManager(); final String email_address = configManager.getPropValues("gmail_address"); final String password = configManager.getPropValues("gmail_pw"); try { Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); // Session session = Session.getDefaultInstance(props, null); Session session = Session.getInstance(props, new GMailAuthenticator(email_address, password)); store = session.getStore("imaps"); store.connect("imap.gmail.com", email_address, password); folder = store.getFolder("Inbox"); folder.open(Folder.READ_WRITE); // Message messages[] = folder.getMessages(); // search for all "unseen" messages Flags seen = new Flags(Flags.Flag.SEEN); FlagTerm unseenFlagTerm = new FlagTerm(seen, false); Message messages[] = folder.search(unseenFlagTerm); for (int i = 0; i < messages.length; i++) { folder.getMessage( messages[i].getMessageNumber()); // this will mark the retrieved messages as READ } String s = updateEmailrepository(messages); // System.out.println(s); StringTerm st = new StringTermImpl(s); return st; } catch (Exception e) { System.out.println(e.toString()); } finally { if (folder != null) { folder.close(true); } } return null; }
public void sendEmails(Homework hw, ArrayList<Student> students) { System.out.println("se apeleza"); String from = "*****@*****.**"; String host = "localhost"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.put("mail.smtp.port", "25"); Session session = Session.getDefaultInstance(properties); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); for (Student s : students) { System.out.println("baga mesaj catre" + s.getEmail()); message.addRecipient(Message.RecipientType.TO, new InternetAddress(s.getEmail())); } message.setSubject("Homework"); // Send the actual HTML message, as big as you like message.setContent( "<h1>This is a test mail.</h1>" + "<p> It's a program I am developing and I just try to play with the mail API.<p>" + "<p> If you're receiving this, please ignore it!</p>" + "<p> You're homework is: </p>" + "<p>" + hw.getDescription() + "</p>" + "<p> Due Date: " + hw.getDueDate() + "</p>", "text/html"); // Send message Transport.send(message); System.out.println(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } }
public static void main(String args[]) throws Exception { // String host = args[0]; // String username = args[1]; // String password = args[2]; String host = "triggeremails.com"; String username = "******"; String password = "******"; // Get session Session session = Session.getInstance(System.getProperties(), null); // Get the store Store store = session.getStore("pop3"); store.connect(host, username, password); // Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // Get directory Message message[] = folder.getMessages(); for (int i = 0, n = message.length; i < n; i++) { System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject()); System.out.println("Do you want to delete message? [YES to delete]"); String line = reader.readLine(); // Mark as deleted if appropriate if ("YES".equals(line)) { message[i].setFlag(Flags.Flag.DELETED, true); } } // Close connection folder.close(true); store.close(); }
private static void sendFromGMail( String from, String pass, String to, String subject, String body) { Properties props = System.getProperties(); String host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); // InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses /*for( int i = 0; i < to.length; i++ ) { toAddress[i] = new InternetAddress(to[i]); }*/ /*for( int i = 0; i < toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress[i]); }*/ message.setSubject(subject); message.setText(body); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (AddressException ae) { ae.printStackTrace(); } catch (MessagingException me) { me.printStackTrace(); } }
// Dovrebbe inviare una mail, not tested public void inviteUser(String email) throws SQLException, EmailException { String to; to = testEmail(email); String from = "*****@*****.**"; String host = "localhost"; // testing Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); Session mailSession = Session.getDefaultInstance(properties); try { MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Sei stato invitato ad iscriverti a" + " Phd-platform."); message.setText("localhost:8080/phd-platform/register.jsp"); // test Transport.send(message); } catch (MessagingException ex) { ex.printStackTrace(); } }
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
public static void ClaimsMsgShow( java.lang.String argvs[], Folder folder, Store store, biz.systempartners.claims.ClaimsViewer claimsViewer) { if (claimsViewer == null) {} int msgnum = -1; int optind = 0; InputStream msgStream = System.in; if (argvs != null) { for (optind = 0; optind < argvs.length; optind++) { if (argvs[optind].equals("-T")) { protocol = argvs[++optind]; } else if (argvs[optind].equals("-H")) { host = argvs[++optind]; } else if (argvs[optind].equals("-U")) { user = argvs[++optind]; } else if (argvs[optind].equals("-P")) { password = argvs[++optind]; } else if (argvs[optind].equals("-v")) { verbose = true; } else if (argvs[optind].equals("-D")) { debug = true; } else if (argvs[optind].equals("-f")) { mbox = argvs[++optind]; } else if (argvs[optind].equals("-L")) { url = argvs[++optind]; } else if (argvs[optind].equals("-p")) { port = Integer.parseInt(argvs[++optind]); } else if (argvs[optind].equals("-s")) { showStructure = true; } else if (argvs[optind].equals("-S")) { saveAttachments = true; } else if (argvs[optind].equals("-m")) { showMessage = true; } else if (argvs[optind].equals("-a")) { showAlert = true; } else if (argvs[optind].equals("--")) { optind++; break; } else if (argvs[optind].startsWith("-")) { System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]"); System.out.println("\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]"); System.out.println("or msgshow -m [-v] [-D] [-s] [-S] < msg"); System.exit(1); } else { break; } } } try { if (optind < argvs.length) msgnum = Integer.parseInt(argvs[optind]); // msgnum = 1; // Get a Properties object Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); session.setDebug(debug); if (showMessage) { MimeMessage msg = new MimeMessage(session, msgStream); dumpPart(msg, claimsViewer); // System.exit(0); } /* // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); if (showAlert) { store.addStoreListener(new StoreListener() { public void notification(StoreEvent e) { String s; if (e.getMessageType() == StoreEvent.ALERT) s = "ALERT: "; else s = "NOTICE: "; System.out.println(s + e.getMessage()); } }); } 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, port, user, password); else store.connect(); } // Open the Folder Folder folder = store.getDefaultFolder(); if (folder == null) { System.out.println("No default folder"); System.exit(1); } */ // folder = folder.getFolder(mbox); if (folder == null) { System.out.println("Invalid folder"); System.exit(1); } // try to open read/write and if that fails try read-only try { folder.open(Folder.READ_WRITE); } catch (MessagingException ex) { folder.open(Folder.READ_ONLY); } int totalMessages = folder.getMessageCount(); if (totalMessages == 0) { System.out.println("Empty folder"); folder.close(false); store.close(); System.exit(1); } if (verbose) { int newMessages = folder.getNewMessageCount(); System.out.println("Total messages = " + totalMessages); System.out.println("New messages = " + newMessages); System.out.println("-------------------------------"); } if (msgnum == -1) { // Attributes & Flags for all messages .. Message[] msgs = folder.getMessages(); // Use a suitable FetchProfile FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(msgs, fp); for (int i = 0; i < msgs.length; i++) { System.out.println("--------------------------"); System.out.println("MESSAGE #" + (i + 1) + ":"); dumpEnvelope(msgs[i]); // dumpPart(msgs[i]); } } else { Message[] msgs = folder.getMessages(); for (int n = 0; n < msgs.length; n++) { System.out.println("Getting message number: " + n + 1); Message m = null; try { m = folder.getMessage(msgnum + 1); // m.setDisposition( dumpPart(m, claimsViewer); // m.setExpunged(true); } catch (IndexOutOfBoundsException iex) { System.out.println("Message number out of range"); } } folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true); } // folder.expunge(); folder.close(true); store.close(); } catch (Exception ex) { System.out.println("Oops, got exception! " + ex.getMessage()); ex.printStackTrace(); // System.exit(1); } // System.exit(0); }
public boolean send() { try { // creamos las propiedades del mail Properties propiedades = System.getProperties(); propiedades.put("mail.smtp.host", hostSmtp); propiedades.put("mail.smtp.auth", "true"); propiedades.put("mail.smtp.port", puertoSMTP); // creamos la sesión para enviar el mail SMTPAuthentication auth = new SMTPAuthentication(); Session mailSesion = Session.getInstance(propiedades, auth); // creamos el mensaje MimeMessage mens = new MimeMessage(mailSesion); // Definimos la dirección del remitente mens.setFrom(new InternetAddress(this.origen)); // creamos un array de las direcciones de los destinatarios InternetAddress[] addressTo = new InternetAddress[this.direcciones.size()]; for (int i = 0; i < this.direcciones.size(); i++) { addressTo[i] = new InternetAddress((String) this.direcciones.get(i)); } // definimos los destinatarios mens.addRecipients(Message.RecipientType.TO, addressTo); // definiemos la fecha de envio mens.setSentDate(new Date()); // Definimos el asunto mens.setSubject(asunto); Multipart multipart = new MimeMultipart(); MimeBodyPart texto = new MimeBodyPart(); texto.setContent(this.mensaje, "text/html"); multipart.addBodyPart(texto); if (this.rutaAdjunto != null) { BodyPart adjunto = new MimeBodyPart(); adjunto.setDataHandler(new DataHandler(new FileDataSource(this.rutaAdjunto))); adjunto.setFileName(this.nombreAdjunto); multipart.addBodyPart(adjunto); } // Definimos el cuerpo del mensaje mens.setContent(multipart); // Creamos el objeto transport con el método Transport transporte = mailSesion.getTransport("smtp"); // enviamos el correo transporte.send(mens); } catch (AddressException ex) { ex.printStackTrace(); return false; } catch (SendFailedException ex) { ex.printStackTrace(); return false; } catch (MessagingException ex) { ex.printStackTrace(); return false; } catch (Exception ex) { ex.printStackTrace(); return false; } return true; }
public static void main(String argv[]) { int optind; String subject = null; String from = null; boolean or = false; boolean today = false; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = 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("-or")) { or = true; } else if (argv[optind].equals("-D")) { debug = true; } else if (argv[optind].equals("-f")) { mbox = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-subject")) { subject = argv[++optind]; } else if (argv[optind].equals("-from")) { from = argv[++optind]; } else if (argv[optind].equals("-today")) { today = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println( "Usage: search [-D] [-L url] [-T protocol] [-H host] " + "[-U user] [-P password] [-f mailbox] " + "[-subject subject] [-from from] [-or] [-today]"); System.exit(1); } else { break; } } try { if ((subject == null) && (from == null) && !today) { System.out.println("Specify either -subject, -from or -today"); System.exit(1); } // Get a Properties object Properties props = System.getProperties(); // Get a Session object Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // 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(); } // Open the Folder Folder folder = store.getDefaultFolder(); if (folder == null) { System.out.println("Cant find default namespace"); System.exit(1); } folder = folder.getFolder(mbox); if (folder == null) { System.out.println("Invalid folder"); System.exit(1); } folder.open(Folder.READ_ONLY); SearchTerm term = null; if (subject != null) term = new SubjectTerm(subject); if (from != null) { FromStringTerm fromTerm = new FromStringTerm(from); if (term != null) { if (or) term = new OrTerm(term, fromTerm); else term = new AndTerm(term, fromTerm); } else term = fromTerm; } if (today) { ReceivedDateTerm dateTerm = new ReceivedDateTerm(ComparisonTerm.EQ, new Date()); if (term != null) { if (or) term = new OrTerm(term, dateTerm); else term = new AndTerm(term, dateTerm); } else term = dateTerm; } Message[] msgs = folder.search(term); System.out.println("FOUND " + msgs.length + " MESSAGES"); if (msgs.length == 0) // no match System.exit(1); // Use a suitable FetchProfile FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); folder.fetch(msgs, fp); for (int i = 0; i < msgs.length; i++) { System.out.println("--------------------------"); System.out.println("MESSAGE #" + (i + 1) + ":"); dumpPart(msgs[i]); } folder.close(false); store.close(); } catch (Exception ex) { System.out.println("Oops, got exception! " + ex.getMessage()); ex.printStackTrace(); } System.exit(1); }
@Override public void contextInitialized(ServletContextEvent arg0) { final String S_ProcName = "contextInitialized"; Properties props = System.getProperties(); if (null == CFBamSchemaPool.getSchemaPool()) { try { Context ctx = new InitialContext(); String poolClassName = (String) ctx.lookup("java:comp/env/CFBam24PoolClass"); if ((poolClassName == null) || (poolClassName.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24PoolClass"); } Class poolClass = Class.forName(poolClassName); if (poolClass == null) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "CFBam24PoolClass \"" + poolClassName + "\" not found."); } Object obj = poolClass.newInstance(); if (obj instanceof CFBamSchemaPool) { CFBamSchemaPool newPool = (CFBamSchemaPool) obj; newPool.setConfigurationFile(null); newPool.setJndiName("java:comp/env/CFBam24Connection"); CFBamSchemaPool.setSchemaPool(newPool); } else { throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Problems constructing an instance of " + poolClassName); } String smtpHost = (String) ctx.lookup("java:comp/env/CFBam24SmtpHost"); if ((smtpHost == null) || (smtpHost.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpHost"); } props.setProperty("mail.smtp.host", smtpHost); String smtpStartTLS = (String) ctx.lookup("java:comp/env/CFBam24SmtpStartTLS"); if ((smtpHost == null) || (smtpHost.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpStartTLS"); } props.setProperty("mail.smtp.starttls.enable", smtpStartTLS); String smtpSocketFactoryClass = (String) ctx.lookup("java:comp/env/CFBam24SmtpSocketFactoryClass"); if ((smtpSocketFactoryClass == null) || (smtpSocketFactoryClass.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpSocketFactoryClass"); } props.setProperty("mail.smtp.socketFactory.class", smtpSocketFactoryClass); props.setProperty("mail.smtp.socketFactory.fallback", "false"); String smtpPort = (String) ctx.lookup("java:comp/env/CFBam24SmtpPort"); if ((smtpPort == null) || (smtpPort.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpPort"); } props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.port", smtpPort); props.setProperty("mail.smtps.auth", "true"); props.put("mail.smtps.quitwait", "false"); String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFBam24SmtpEmailFrom"); if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpEmailFrom"); } smtpUsername = (String) ctx.lookup("java:comp/env/CFBam24SmtpUsername"); if ((smtpUsername == null) || (smtpUsername.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpUsername"); } smtpPassword = (String) ctx.lookup("java:comp/env/CFBam24SmtpPassword"); if ((smtpPassword == null) || (smtpPassword.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpPassword"); } String serverKeyStore; try { serverKeyStore = (String) ctx.lookup("java:comp/env/CFBam24ServerKeyStore"); } catch (NamingException e) { serverKeyStore = null; } String keyStorePassword; try { keyStorePassword = (String) ctx.lookup("java:comp/env/CFBam24KeyStorePassword"); } catch (NamingException e) { keyStorePassword = null; } String keyName; try { keyName = (String) ctx.lookup("java:comp/env/CFBam24KeyName"); } catch (NamingException e) { keyName = null; } String keyPassword; try { keyPassword = (String) ctx.lookup("java:comp/env/CFBam24KeyPassword"); } catch (NamingException e) { keyPassword = null; } if (((serverKeyStore != null) && (serverKeyStore.length() > 0)) && (keyStorePassword != null) && ((keyName != null) && (keyName.length() > 0)) && (keyPassword != null)) { KeyStore keyStore = null; File keystoreFile = new File(serverKeyStore); if (!keystoreFile.exists()) { throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "CFBam24ServerKeyStore file \"" + serverKeyStore + "\" does not exist."); } else if (!keystoreFile.isFile()) { throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "CFBam24ServerKeyStore file \"" + serverKeyStore + "\" is not a file."); } else if (!keystoreFile.canRead()) { throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "Permission denied attempting to read CFBam24ServerKeyStore file \"" + serverKeyStore + "\"."); } try { keyStore = KeyStore.getInstance("jceks"); char[] caPassword = keyStorePassword.toCharArray(); FileInputStream input = new FileInputStream(serverKeyStore); keyStore.load(input, caPassword); input.close(); Certificate publicKeyCertificate = keyStore.getCertificate(keyName); if (publicKeyCertificate == null) { throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "Could not read CFBam24KeyName \"" + keyName + "\" from CFBam24ServerKeyStore file \"" + serverKeyStore + "\"."); } publicKey = publicKeyCertificate.getPublicKey(); char[] caKeyPassword = keyPassword.toCharArray(); Key key = keyStore.getKey(keyName, caKeyPassword); if (key instanceof PrivateKey) { privateKey = (PrivateKey) key; } else { throw CFLib.getDefaultExceptionFactory() .newUnsupportedClassException(getClass(), S_ProcName, "key", key, "PrivateKey"); } getServerInfo(); } catch (CertificateException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not open keystore due to CertificateException -- " + x.getMessage(), x); } catch (IOException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not open keystore due to IOException -- " + x.getMessage(), x); } catch (KeyStoreException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not open keystore due to KeyStoreException -- " + x.getMessage(), x); } catch (NoSuchAlgorithmException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not open keystore due to NoSuchAlgorithmException -- " + x.getMessage(), x); } catch (UnrecoverableKeyException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not access key due to UnrecoverableKeyException -- " + x.getMessage(), x); } catch (RuntimeException x) { publicKey = null; privateKey = null; throw x; } } else if ((serverKeyStore != null) || (keyStorePassword != null) || (keyName != null) || (keyPassword != null)) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "All or none of CFBam24ServerKeyStore, " + "CFBam24KeyStorePassword, " + "CFBam24KeyName, and " + "CFBam24KeyPassword must be configured"); } else { getServerInfo(); try { serverInfo.initServerKeys(); } catch (Exception x) { throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught " + x.getClass().getName() + " during initServerKeys() -- " + x.getMessage(), x); } } } catch (ClassNotFoundException e) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught ClassNotFoundException -- " + e.getMessage(), e); } catch (IllegalAccessException e) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught IllegalAccessException trying to construct newInstance() -- " + e.getMessage(), e); } catch (InstantiationException e) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught InstantiationException trying to construct newInstance() -- " + e.getMessage(), e); } catch (NamingException e) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught NamingException -- " + e.getMessage(), e); } } }
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); }