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();
    }
  }
Exemple #2
3
  public void sendSimpleEmailAuthenticated(
      String SMTPHost,
      String userName,
      String password,
      String subject,
      String body,
      String toAddress,
      String fromAddress)
      throws MessagingException {
    SMTP_AUTH_USER = userName;
    SMTP_AUTH_PWD = password;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTPHost);
    props.put("mail.smtp.auth", "true");

    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);

    MimeMessage message = new MimeMessage(session);

    message.setSubject(subject);
    message.setContent(body, "text/plain");

    message.setFrom(new InternetAddress(fromAddress));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));

    Transport.send(message);
  }
  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 {
    Properties props = new Properties();
    try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) {
      props.load(in);
    }
    List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8"));

    String from = lines.get(0);
    String to = lines.get(1);
    String subject = lines.get(2);

    StringBuilder builder = new StringBuilder();
    for (int i = 3; i < lines.size(); i++) {
      builder.append(lines.get(i));
      builder.append("\n");
    }

    Console console = System.console();
    String password = new String(console.readPassword("Password: "));

    Session mailSession = Session.getDefaultInstance(props);
    // mailSession.setDebug(true);
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(builder.toString());
    Transport tr = mailSession.getTransport();
    try {
      tr.connect(null, password);
      tr.sendMessage(message, message.getAllRecipients());
    } finally {
      tr.close();
    }
  }
  public void send() {

    Properties props = new Properties();

    props.setProperty("mail.transport.protocol", "smtp");
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    Session mailSession = Session.getDefaultInstance(props);
    // mailSession.setDebug(true);
    Transport transport;
    try {
      transport = mailSession.getTransport();

      MimeMessage message = new MimeMessage(mailSession);
      message.setFrom(new InternetAddress(userName));
      message.setSubject(subject);

      message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

      if (!cc.equals("")) {
        message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
      }
      if (!bcc.equals("")) {
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc));
      }

      // create the message part
      MimeBodyPart messageBodyPart = new MimeBodyPart();

      // fill message
      messageBodyPart.setText(content);

      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);
      if (fList != null) {
        Iterator<File> i = fList.iterator();
        // part two is attachment
        while (i.hasNext()) {
          File file = (File) i.next();
          messageBodyPart = new MimeBodyPart();
          DataSource source = new FileDataSource(file);
          messageBodyPart.setDataHandler(new DataHandler(source));
          messageBodyPart.setFileName(file.getName());
          multipart.addBodyPart(messageBodyPart);
        }
      }
      // Put parts in message
      message.setContent(multipart);

      Transport.send(message);

      transport.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public static void sfSendEmail(String subject, String message) throws Exception {

    String SMTP_HOST_NAME = "smtp.gmail.com";
    String SMTP_PORT = "465";
    // message = "Test Email Notification From Monitor";
    // subject = "Test Email Notification From Monitor";
    String from = "*****@*****.**";
    String[] recipients = {
      "*****@*****.**", "*****@*****.**", "*****@*****.**"
    };
    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    // String[] recipients = { "*****@*****.**"};
    // String[] recipients = { "*****@*****.**", "*****@*****.**",
    // "*****@*****.**", "*****@*****.**", "*****@*****.**",
    // "*****@*****.**", "*****@*****.**"};
    // String[] recipients = {"*****@*****.**"};

    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

    boolean debug = true;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    // props.put("mail.debug", "true");
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");

    Session session =
        Session.getDefaultInstance(
            props,
            new Authenticator() {

              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "*****@*****.**", "els102sensorweb");
              }
            });

    // session.setDebug(debug);

    Message msg = new MimeMessage(session);
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);

    System.out.println("Sucessfully Sent mail to All Users");
  }
Exemple #8
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
Exemple #9
0
  public void mail(String toAddress, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.ssl.enable", true);
    Authenticator authenticator = null;
    if (login) {
      props.put("mail.smtp.auth", true);
      authenticator =
          new Authenticator() {
            private PasswordAuthentication pa = new PasswordAuthentication(username, password);

            @Override
            public PasswordAuthentication getPasswordAuthentication() {
              return pa;
            }
          };
    }

    Session s = Session.getInstance(props, authenticator);
    s.setDebug(debug);
    MimeMessage email = new MimeMessage(s);
    try {
      email.setFrom(new InternetAddress(from));
      email.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
      email.setSubject(subject);
      email.setSentDate(new Date());
      email.setText(body);
      Transport.send(email);
    } catch (MessagingException ex) {
      ex.printStackTrace();
    }
  }
  public void postMail(String recipients[], String subject, String message, String from)
      throws MessagingException {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.timeout", 60000);

    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);

    session.setDebug(debug);

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

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/html");
    Transport.send(msg);
  }
Exemple #11
0
  public void send() {
    // Your SMTP server address here.
    String smtpHost = "myserver.jeffcorp.com";
    // The sender's email address
    String from = "*****@*****.**";
    // The recepients email address
    String to = "*****@*****.**";

    Properties props = new Properties();
    // The protocol to use is SMTP
    props.put("mail.smtp.host", smtpHost);

    Session session = Session.getDefaultInstance(props, null);

    try {
      InternetAddress[] address = {new InternetAddress(to)};
      MimeMessage message;

      message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));

      message.setRecipients(Message.RecipientType.TO, to);
      message.setSubject("Hello from Jeff");
      message.setSentDate(sendDate);
      message.setText("Hello Jeff, \nHow are things going?");

      Transport.send(message);

      System.out.println("email has been sent.");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
 public void sendMessage() throws FrameworkExecutionException {
   try {
     Transport.send(message);
   } catch (MessagingException me) {
     // do logging here
     throw new FrameworkExecutionException(me);
   }
 }
  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();
    }
  }
  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();
    }
  }
  @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);
  }
Exemple #17
0
 /**
  * Sends the given mail message with a given MIME format.
  *
  * @param from Sender address
  * @param replyTo Reply-to address
  * @param to Array of target addresses
  * @param cc Array of CC addresses - or null
  * @param subject Subject
  * @param message Message
  * @param mimeType Mime-type of the message; if null, sends text/plain.
  * @throws MessagingException If any failure occurs in contacting mail server etc.
  */
 public static void send(
     String from,
     String replyTo,
     String[] to,
     String[] cc,
     String subject,
     String message,
     String mimeType)
     throws MessagingException {
   MimeMessage mm = createMessage(from, replyTo, to, cc, subject);
   if (mimeType == null) {
     mm.setText(message, "UTF-8");
   } else {
     mm.setDataHandler(new DataHandler(message, mimeType));
   }
   Transport.send(mm);
 }
Exemple #18
0
  public void sendSimpleEmail(
      String SMTPHost, String subject, String body, String toAddress, String fromAddress)
      throws MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", SMTPHost);

    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);

    message.setSubject(subject);
    message.setText(body);

    message.setFrom(new InternetAddress(fromAddress));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));

    Transport.send(message);
  }
  public static void sendSSLMessage(
      String recipients[], String subject, String message, String from) throws MessagingException {
    boolean debug = true;

    /*Da errore ma non c'e' da preoccuparsi*/
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");

    Session session =
        Session.getDefaultInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("*****@*****.**", "magicrestaurant");
              }
            });

    session.setDebug(debug);

    Message msg = new MimeMessage(session);
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
  }
  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();
    }
  }
  // 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();
    }
  }
  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);
  }
  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
Exemple #24
0
  public static synchronized boolean sendMail(
      String userName,
      String passWord,
      String host,
      String port,
      String starttls,
      String auth,
      boolean debug,
      String socketFactoryClass,
      String fallback,
      String[] to,
      String[] cc,
      String[] bcc,
      String subject,
      String text) {
    Properties props = new Properties();
    // Properties props=System.getProperties();
    props.put("mail.smtp.user", userName);
    props.put("mail.smtp.host", host);
    if (!"".equals(port)) {
      props.put("mail.smtp.port", port);
    }
    if (!"".equals(starttls)) {
      props.put("mail.smtp.starttls.enable", starttls);
    }
    props.put("mail.smtp.auth", auth);
    if (debug) {
      props.put("mail.smtp.debug", "true");
    } else {
      props.put("mail.smtp.debug", "false");
    }
    if (!"".equals(port)) {
      props.put("mail.smtp.socketFactory.port", port);
    }
    if (!"".equals(socketFactoryClass)) {
      props.put("mail.smtp.socketFactory.class", socketFactoryClass);
    }
    if (!"".equals(fallback)) {
      props.put("mail.smtp.socketFactory.fallback", fallback);
    }

    try {
      Session session = Session.getDefaultInstance(props, null);
      session.setDebug(debug);
      MimeMessage msg = new MimeMessage(session);
      msg.setText(text);
      msg.setSubject(subject);
      msg.setFrom(new InternetAddress("*****@*****.**"));
      for (int i = 0; i < to.length; i++) {
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
      }
      msg.saveChanges();
      Transport transport = session.getTransport("smtp");
      transport.connect(host, userName, passWord);
      transport.sendMessage(msg, msg.getAllRecipients());
      transport.close();
      return true;
    } catch (Exception mex) {
      mex.printStackTrace();
      return false;
    }
  }
  public static void sendEmail(String subject, String message) throws Exception {
    /*
    String mailhost = "mail.vancouver.wsu.edu";
    String cc = null;
    String bcc = null;
    boolean debug = false;
    String file = null;
    String mailer = "msgsend";
    String sender = "mail.vancouver.wsu.edu";


       Properties props = System.getProperties();

       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 (sender != null)
    msg.setFrom(new InternetAddress(sender));
       else
    msg.setFrom();

       msg.setRecipients(Message.RecipientType.TO,
    			InternetAddress.parse(receivers[0], false));

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

       msg.setSubject(subject);

       String text = content;

       if (file != null) {
    // Attach the specified file.
    // We need a multipart message to hold the attachment.
    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(text);
    MimeBodyPart mbp2 = new MimeBodyPart();
    mbp2.attachFile(file);
    MimeMultipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);
    mp.addBodyPart(mbp2);
    msg.setContent(mp);
       } else {
    // If the desired charset is known, you can use
    // setText(text, charset)
    msg.setText(text);
       }

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

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

       System.out.println("\nMail was sent successfully.");
    */

    // Xiaogang: checkbox
    // System.out.println("sendemail"+MainFrame.EMAIL_ENABLE);
    if (MainFrame.EMAIL_ENABLE == false) return;

    String SMTP_HOST_NAME = "smtp.gmail.com";
    String SMTP_PORT = "465";
    // message = "Test Email Notification From Monitor";
    // subject = "Test Email Notification From Monitor";
    String from = "*****@*****.**";
    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    String[] recipients = {
      "*****@*****.**", "*****@*****.**", "*****@*****.**"
    };
    // String[] recipients = { "*****@*****.**"};
    // String[] recipients = { , "*****@*****.**", "*****@*****.**",
    // "*****@*****.**", "*****@*****.**"};
    // String[] recipients = {"*****@*****.**"};

    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

    boolean debug = true;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", "true");
    // props.put("mail.debug", "true");
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");

    Session session =
        Session.getDefaultInstance(
            props,
            new Authenticator() {

              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "*****@*****.**", "els102sensorweb");
              }
            });

    // session.setDebug(debug);

    Message msg = new MimeMessage(session);
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
      addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);

    System.out.println("Sucessfully Sent mail to All Users");
  }
Exemple #26
0
  public static boolean sendMail(
      String userName,
      String passWord,
      String host,
      String port,
      String starttls,
      String auth,
      boolean debug,
      String socketFactoryClass,
      String fallback,
      String[] to,
      String[] cc,
      String[] bcc,
      String subject,
      String text,
      String attachmentPath,
      String attachmentName) {

    // Object Instantiation of a properties file.
    Properties props = new Properties();

    props.put("mail.smtp.user", userName);

    props.put("mail.smtp.host", host);

    if (!"".equals(port)) {
      props.put("mail.smtp.port", port);
    }

    if (!"".equals(starttls)) {
      props.put("mail.smtp.starttls.enable", starttls);
      props.put("mail.smtp.auth", auth);
    }

    if (debug) {

      props.put("mail.smtp.debug", "true");

    } else {

      props.put("mail.smtp.debug", "false");
    }

    if (!"".equals(port)) {
      props.put("mail.smtp.socketFactory.port", port);
    }
    if (!"".equals(socketFactoryClass)) {
      props.put("mail.smtp.socketFactory.class", socketFactoryClass);
    }
    if (!"".equals(fallback)) {
      props.put("mail.smtp.socketFactory.fallback", fallback);
    }

    try {

      Session session = Session.getDefaultInstance(props, null);

      session.setDebug(debug);

      MimeMessage msg = new MimeMessage(session);

      msg.setText(text);

      msg.setSubject(subject);

      Multipart multipart = new MimeMultipart();
      MimeBodyPart messageBodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource(attachmentPath);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(attachmentName);
      multipart.addBodyPart(messageBodyPart);

      msg.setContent(multipart);
      msg.setFrom(new InternetAddress(userName));

      for (int i = 0; i < to.length; i++) {
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
      }

      for (int i = 0; i < cc.length; i++) {
        msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
      }

      for (int i = 0; i < bcc.length; i++) {
        msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
      }

      msg.saveChanges();

      Transport transport = session.getTransport("smtp");

      transport.connect(host, userName, passWord);

      transport.sendMessage(msg, msg.getAllRecipients());

      transport.close();

      return true;

    } catch (Exception mex) {
      mex.printStackTrace();
      return false;
    }
  }
  public boolean sendMessage() {
    Properties properties = new Properties();
    properties.put("mail.smtp.host", mailHost);
    properties.put("mail.from", Source);
    Session session = Session.getInstance(properties, null);
    try {
      Message message = new MimeMessage(session);
      InternetAddress[] addressTO = null;
      if (this.Destination != null && this.Destination.length() != 0) {
        StringTokenizer TOList = getTokenizer(this.Destination);
        addressTO = new InternetAddress[TOList.countTokens()];
        for (int i = 0; i < addressTO.length; i++) {
          addressTO[i] = new InternetAddress(TOList.nextToken());
          message.addRecipient(Message.RecipientType.TO, addressTO[i]);
        }
      }

      if (this.MsgCC != null && this.MsgCC.length() != 0) {
        StringTokenizer CCList = getTokenizer(this.MsgCC);
        InternetAddress[] addressCC = new InternetAddress[CCList.countTokens()];
        for (int i = 0; i < addressCC.length; i++) {
          addressCC[i] = new InternetAddress(CCList.nextToken());
          message.addRecipient(Message.RecipientType.CC, addressCC[i]);
        }
      }
      message.setFrom(new InternetAddress(Source));
      message.setSubject(Subject);
      Content = getHtmlHeader() + Content + getHtmlFooter();
      Content = Content.replaceAll("\\{style\\}", MailStyle);

      BodyPart messageBodyPart = new MimeBodyPart();

      messageBodyPart.setText(Content);
      messageBodyPart.setContent(Content, "text/html");

      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);

      Iterator it = this.BinaryAttachments.iterator();
      while (it.hasNext()) {
        ByteArrayDataSource bads = (ByteArrayDataSource) it.next();

        messageBodyPart = new MimeBodyPart();
        // messageBodyPart.setDataHandler(new DataHandler(new FileDataSource("c:/test/tom.jpg")));
        messageBodyPart.setDataHandler(new DataHandler(bads));
        messageBodyPart.setFileName(bads.getName());

        multipart.addBodyPart(messageBodyPart);
      }
      message.setContent(multipart);

      Transport transport = session.getTransport(addressTO[0]);
      transport.addConnectionListener(new ConnectionHandler());
      transport.addTransportListener(new TransportHandler());
      transport.connect();
      transport.send(message);
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
Exemple #28
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;
  }