Exemplo n.º 1
2
  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();
    }
  }
Exemplo n.º 2
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String email = request.getParameter("email");

    Properties pros = System.getProperties();
    pros.setProperty("mail.smtp.host", "localhost");

    Session mailsession = Session.getDefaultInstance(properties);

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    String to = email;
    String from = "*****@*****.**"; // enter the senders email
    String subject = ""; // enter a subject
    String body = "";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(from));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      msg.setSubject(subject);
      msg.setText(body);
      Transport.send(message);
    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 3
0
 public static void main(String[] args) throws Exception {
   MailClientForCitiz client = new MailClientForCitiz();
   client.init();
   client.sendMessage(client.fromAddr, client.toAddr);
   client.receiveMessage();
   client.close();
   System.exit(0);
 }
Exemplo n.º 4
0
 /** set the file */
 public void setFile(String filename) {
   fds = new FileDataSource(filename);
   System.out.println("DCHTest2: FileDataSource created");
   if (!fds.getContentType().equals("text/plain")) {
     System.out.println("Type must be text/plain");
     System.exit(1);
   }
 }
Exemplo n.º 5
0
  /** set the mailcap file in the CMD Map */
  public void setMailcap(String mailcap) {

    try {
      cmdMap = new MailcapCommandMap(mailcap);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Exemplo n.º 6
0
  /** main function */
  public static void main(String args[]) {
    DCHTest2 test = new DCHTest2();

    if (args.length < 2) {
      System.out.println("usage: DCHTest2 file.txt mailcap");
      System.exit(1);
    }

    // first let's get a DataSource

    test.setFile(args[0]);

    test.setMailcap(args[1]);
    test.doit();
  }
  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();
    }
  }
  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();
    }
  }
Exemplo n.º 9
0
  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
Exemplo n.º 10
0
  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);
  }
Exemplo n.º 11
0
  public static void dumpPart(Part p, biz.systempartners.claims.ClaimsViewer claimsViewer)
      throws Exception {
    if (p instanceof Message) dumpEnvelope((Message) p);

    /**
     * Dump input stream ..
     *
     * <p>InputStream is = p.getInputStream(); // If "is" is not already buffered, wrap a
     * BufferedInputStream // around it. if (!(is instanceof BufferedInputStream)) is = new
     * BufferedInputStream(is); int c; while ((c = is.read()) != -1) System.out.write(c);
     */
    String ct = p.getContentType();
    try {
      pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
    } catch (ParseException pex) {
      pr("BAD CONTENT-TYPE: " + ct);
    }
    String filename = p.getFileName();
    if (filename != null) pr("FILENAME: " + filename);

    /*
     * Using isMimeType to determine the content type avoids
     * fetching the actual content data until we need it.
     */
    if (p.isMimeType("text/plain")) {
      pr("This is plain text");
      pr("---------------------------");
      if (!showStructure && !saveAttachments) System.out.println((String) p.getContent());
    } else if (p.isMimeType("multipart/*")) {
      pr("This is a Multipart");
      pr("---------------------------");
      Multipart mp = (Multipart) p.getContent();
      level++;
      int count = mp.getCount();
      for (int i = 0; i < count; i++) dumpPart(mp.getBodyPart(i), claimsViewer);
      level--;
    } else if (p.isMimeType("message/rfc822")) {
      pr("This is a Nested Message");
      pr("---------------------------");
      level++;
      dumpPart((Part) p.getContent(), claimsViewer);
      level--;
    } else {
      if (!showStructure && !saveAttachments) {
        /*
         * If we actually want to see the data, and it's not a
         * MIME type we know, fetch it and check its Java type.
         */
        Object o = p.getContent();
        if (o instanceof String) {
          pr("This is a string");
          pr("---------------------------");
          System.out.println((String) o);
        } else if (o instanceof InputStream) {
          pr("This is just an input stream");
          pr("---------------------------");
          InputStream is = (InputStream) o;
          int c;
          while ((c = is.read()) != -1) System.out.write(c);
        } else {
          pr("This is an unknown type");
          pr("---------------------------");
          pr(o.toString());
        }
      } else {
        // just a separator
        pr("---------------------------");
      }
    }

    /*
     * If we're saving attachments, write out anything that
     * looks like an attachment into an appropriately named
     * file.  Don't overwrite existing files to prevent
     * mistakes.
     */
    if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) {
      String disp = p.getDisposition();
      // many mailers don't include a Content-Disposition
      if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
        if (filename == null) filename = "Attachment" + attnum++;
        pr("Saving attachment to file " + filename);
        try {
          File f = new File(System.getProperty("user.dir"), filename);
          /*  if (f.exists())
          // XXX - could try a series of names
          throw new IOException("file exists");*/
          OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
          InputStream is = p.getInputStream();
          int c;
          while ((c = is.read()) != -1) os.write(c);
          os.close();
          if (p.isMimeType("text/xml") || p.isMimeType("application/octet-stream")) {
            processBrRequisitionFile(
                f, claimsViewer, claimsViewer.getInvoiceVector(), claimsViewer.getFilesVector());
          }
          System.out.println("I have saved file [" + f.getAbsolutePath() + "]");
        } catch (IOException ex) {
          pr("Failed to save attachment: " + ex);
        }
        pr("---------------------------");
      }
    }
  }
Exemplo n.º 12
0
  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);
  }