Esempio 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();
    }
  }
Esempio n. 2
1
  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 void sendMail(String from, String to, String subject, String Body) {
    Properties props = new Properties();
    // String host="smtp.gmail.com";

    props.put("mail.transport.protocol", protocol);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.auth", auth);
    props.put("mail.smtp.starttls.enable", starttls);
    props.put("mail.smtp.socketFactory.port", socketFactoryPort);
    props.put("mail.smtp.socketFactory.class", socketFactoryClass);
    props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback);

    Session session =
        Session.getDefaultInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    usrname, pasword); // Specify the Username and the PassWord
              }
            });

    MimeMessage message = new MimeMessage(session);
    try {
      InternetAddress addressFrom = new InternetAddress(from);
      message.setFrom(addressFrom);
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject(subject);
      message.setText(Body);
      Transport.send(message);
    } catch (MessagingException ex) {
      System.err.println("Cannot send email. " + ex);
    }
  }
  @Test
  public void shouldReceiveMessageAndSendOutgoingMail() throws Exception {
    // send test message to camel@localhost
    MimeMessage msg = new MimeMessage(session);
    msg.setSubject(SUBJECT);
    msg.setRecipients(RecipientType.TO, "camel@localhost");
    msg.setText(PAYLOAD);

    Transport.send(msg);
    Thread.sleep(500);

    Message[] messages = inbox.getMessages();
    // verify mailbox states, note that mock javamail do not create new
    // folders, so everything goes to same place
    assertEquals(2, messages.length);

    messages = read.getMessages();
    assertEquals(2, messages.length);
    assertEquals(PAYLOAD, messages[0].getContent());
    assertEquals(SUBJECT, messages[0].getSubject());

    messages = riderInbox.getMessages();
    assertEquals(1, messages.length);
    assertEquals("Forwarded message", messages[0].getSubject());
    assertEquals(PAYLOAD, messages[0].getContent());
  }
Esempio n. 5
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();
    }
  }
Esempio n. 6
0
  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();
    }
  }
Esempio n. 7
0
  /**
   * Sends an email out
   *
   * @param fromAddress
   * @param toAddresses
   * @param strSubject
   * @param strMsg
   */
  public void sendMail(
      String fromAddress,
      String strReplyTo,
      String[] toAddresses,
      String strSubject,
      String strMsg) {
    try {
      Properties props = new Properties();
      props.put("mail.smtp.host", SMTP_HOST);
      Session s = Session.getInstance(props, null);

      MimeMessage message = new MimeMessage(s);

      InternetAddress from = new InternetAddress(fromAddress);
      message.setFrom(from);

      InternetAddress[] addressTo = new InternetAddress[toAddresses.length];
      for (int i = 0; i < toAddresses.length; i++) {
        addressTo[i] = new InternetAddress(toAddresses[i]);
      }
      message.addRecipients(RecipientType.BCC, addressTo);

      message.setSubject(strSubject);
      message.setText(strMsg);
      if (strReplyTo != null) {
        InternetAddress[] iAddress = new InternetAddress[] {new InternetAddress(strReplyTo)};
        message.setReplyTo(iAddress);
      }
      Transport.send(message);
    } catch (Exception e) {
      throw new WickerException(e);
    }
  }
  /** Prepares the message to be sent by the email sender */
  protected MimeMessage prepareEmailSenderMessage(
      Session session, String to, String replyTo, String subject, String body) throws Exception {

    MimeMessage message = new MimeMessage(session);

    // From
    InternetAddress fromAddress = new InternetAddress(emailAddress);
    fromAddress.setPersonal(emailPersonalName);
    message.setFrom(fromAddress);

    // Reply to
    InternetAddress[] replyToAddress = new InternetAddress[1];
    replyToAddress[0] = new InternetAddress(replyTo);
    replyToAddress[0].setPersonal(emailPersonalName);
    message.setReplyTo(replyToAddress);

    // To
    InternetAddress toAddress = new InternetAddress(to);
    message.addRecipient(Message.RecipientType.TO, toAddress);

    // Subject/Body
    message.setSubject(subject);
    message.setText(body);

    return message;
  }
Esempio n. 9
0
  // send emails
  public void sendEmail(String to, String mess) {

    try {
      String host = "smtp.gmail.com";
      String username = "******";
      String password = "******";
      String email = "*****@*****.**";

      Properties props = System.getProperties();
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.user", username);
      props.put("mail.smtp.password", password);
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");

      Session s = Session.getDefaultInstance(props, null);
      MimeMessage m = new MimeMessage(s);
      m.setFrom(new InternetAddress(email));

      m.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      m.setSubject("Secret Santa");
      m.setText(mess);

      Transport t = s.getTransport("smtp");
      t.connect(host, 465, username, password);
      t.sendMessage(m, m.getRecipients(Message.RecipientType.TO));
      t.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Esempio n. 10
0
  public static void sendEmail(String toEmail, String subject, String body) {
    try {

      Properties props = System.getProperties();
      props.put("mail.smtp.host", "mail.excellenceserver.com"); // SMTP Host
      //	        props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
      props.put("mail.smtp.port", "27"); // TLS Port
      props.put("mail.smtp.auth", "true"); // enable authentication
      props.put("mail.smtp.starttls.enable", "true"); // enable STARTTLS

      Authenticator auth =
          new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication("*****@*****.**", "user@#123");
            }
          };
      Session session = Session.getInstance(props, auth);

      MimeMessage msg = new MimeMessage(session);
      // set message headers
      msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
      msg.addHeader("format", "flowed");
      msg.addHeader("Content-Transfer-Encoding", "8bit");
      msg.setFrom(new InternetAddress("*****@*****.**", "user@#123"));
      msg.setReplyTo(InternetAddress.parse("*****@*****.**", false));
      msg.setSubject(subject, "UTF-8");
      msg.setText(body, "UTF-8");
      msg.setSentDate(new Date());
      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));

      Transport.send(msg);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 11
0
 /** Sends the message. Uses superclass username, pass, host, etc. */
 public void sendMessage() {
   if (text == null) {
     text = asker.askOpenEnded("Please enter a message to send: ");
   }
   if (destination == null) {
     while (destination == null) {
       try {
         destination =
             new InternetAddress(asker.askOpenEnded("Please enter a message recipient: "));
       } catch (AddressException e) {
         System.out.println("Sorry, you entered an invalid email address.");
       }
     }
   }
   if (subject == null) {
     subject = asker.askOpenEnded("Please enter a subjectJ: ");
   }
   try {
     MimeMessage msg = new MimeMessage(super.session);
     msg.setSubject(this.subject);
     msg.setText(this.text);
     msg.setFrom(new InternetAddress(super.username));
     msg.addRecipient(Message.RecipientType.TO, this.destination);
     Transport t = super.session.getTransport("smtps");
     t.connect(super.host, super.username, super.password);
     t.sendMessage(msg, msg.getAllRecipients());
   } catch (MessagingException mex) {
     throw new MailException(mex.getMessage());
   }
   super.addMessagesToDB();
   System.out.println("Successfully sent message.");
 }
Esempio n. 12
0
  public static boolean sendEmail(String from, String to, String subject, String message) {
    // create a new authenticator for the SMTP server
    EmailUtilsAuthenticator authenticator = new EmailUtilsAuthenticator();

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty(MAIL_SMTP_HOST, Configuration.getSmtpHost());
    // setup the authentication
    properties.setProperty(MAIL_SMTP_AUTH, "true");

    // Get the Session object with the authenticator.
    Session session = Session.getInstance(properties, authenticator);

    try {
      MimeMessage mime = new MimeMessage(session);
      mime.setFrom(new InternetAddress(from));
      mime.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

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

      // Send it
      Transport.send(mime);

      return true;

    } catch (MessagingException mex) {
      logger.error("sendEmail(String, String, String, String) - exception ", mex);
      return false;
    }
  }
Esempio n. 13
0
  private static void sendSimpleEmails(String toUserName, int count)
      throws MessagingException, InterruptedException, IOException {

    Session session = Session.getInstance(getEmailProperties());

    Random random = new Random();
    int emailSize = emails.length;
    for (int i = 1; i <= count; i++) {
      Thread.sleep(10000);

      MimeMessage msg = new MimeMessage(session);

      InternetAddress from = new InternetAddress(emails[random.nextInt(emailSize)]);

      InternetAddress to = new InternetAddress(toUserName);

      msg.setFrom(from);
      msg.addRecipient(Message.RecipientType.TO, to);
      msg.setSentDate(new Date());

      SimpleMessage randomMessage =
          SimpleMessage.values()[random.nextInt(SimpleMessage.values().length)];
      msg.setSubject(randomMessage.name());
      msg.setText(randomMessage.getBody());
      Transport.send(msg);
    }
  }
Esempio n. 14
0
  /**
   * main de prueba
   *
   * @param args Se ignoran.
   */
  public static void main(String[] args) {
    try {
      // Propiedades de la conexión
      Properties props = new Properties();
      props.setProperty("mail.smtp.host", "smtp.gmail.com");
      props.setProperty("mail.smtp.starttls.disable", "true");
      props.setProperty("mail.smtp.auth.plain.disable", "true");
      props.setProperty("mail.smtp.port", "465");
      props.setProperty("mail.smtp.user", "*****@*****.**");
      props.setProperty("mail.smtp.auth", "true");

      // Preparamos la sesion
      Session session = Session.getDefaultInstance(props);
      session.setDebug(true);
      // Construimos el mensaje
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress("*****@*****.**"));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress("*****@*****.**"));
      message.setSubject("Hola");
      message.setText("Mensajito con Java Mail" + "de los buenos." + "poque si");

      // Lo enviamos.
      Transport t = session.getTransport("smtp");
      t.connect("*****@*****.**", "admmphinv2012");
      t.sendMessage(message, message.getAllRecipients());

      // Cierre.
      t.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 private void addAttachments(String msgText, MimeMessage msg) throws MessagingException {
   Enumeration docs = as.getRelatedTopics(getID(), SEMANTIC_EMAIL_ATTACHMENT, 2).elements();
   Multipart mp = null;
   while (docs.hasMoreElements()) {
     BaseTopic doc = (BaseTopic) docs.nextElement();
     if (doc.getType().equals(TOPICTYPE_DOCUMENT)) {
       String sFileName = getProperty(doc, PROPERTY_FILE);
       String sFile = FileServer.repositoryPath(FILE_DOCUMENT) + sFileName;
       MimeBodyPart mbp = new MimeBodyPart();
       FileDataSource ds = new FileDataSource(sFile);
       DataHandler dh = new DataHandler(ds);
       mbp.setDataHandler(dh);
       String sFileDoc = doc.getName();
       if ((sFileDoc != null) && !sFileDoc.equals("")) {
         mbp.setFileName(sFileDoc);
       } else {
         mbp.setFileName(sFileName);
       }
       if (mp == null) {
         mp = new MimeMultipart();
         MimeBodyPart mbpText = new MimeBodyPart();
         mbpText.setText(msgText, "UTF-8");
         mp.addBodyPart(mbpText);
       }
       mp.addBodyPart(mbp);
     }
   }
   // multi part or not
   if (mp != null) {
     msg.setContent(mp);
   } else {
     msg.setText(msgText, "UTF-8");
   }
 }
Esempio n. 16
0
  public void SendEmail(String email, String contestToken) {
    String to = email;
    String from = "Tyumen_ACM_Society";
    String host = "smtp.gmail.com";
    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", host);
    props.put("mail.stmp.user", "*****@*****.**");
    props.put("mail.smtp.password", "475508th");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");

    Session session = Session.getDefaultInstance(props, new SmtpAuthenticator());

    try {
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject("Registration on acm.utmn.ru");
      message.setText(
          "Hello! Thank you for registration on acm.utmn.ru! Use next token to submit tasks: "
              + contestToken);
      Transport t = session.getTransport("smtp");
      t.send(message);
      System.out.println("Message was successfully sent.");
    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
  }
Esempio n. 17
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);
    }
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Session sess = MyHb.getSessionFactory().openSession();
    String uname = request.getParameter("uname");
    String bday = request.getParameter("bday");
    String email = "";
    String pass = "";
    String subject = "Your Password";

    List<Reg> list =
        sess.createCriteria(in.hibernate.Reg.class).add(Restrictions.eq("uname", uname)).list();

    if (!list.isEmpty()) {
      Reg reg = list.get(0);
      if (reg.getBday().equals(bday)) {
        email = reg.getEmail();
        pass = reg.getPass();
        String body = "\nDear ";
        body +=
            reg.getFname()
                + "\n\n Your Password is : "
                + pass
                + "\n\n\n\nThanking You, \nProject Team";
        try {
          Properties props = new Properties();

          props.put("mail.smtp.host", "smtp.gmail.com");
          props.put("mail.smtp.port", 587);
          props.put("mail.smtp.auth", "true");
          props.put("mail.smtp.ssl.enable", "yes");
          props.put("mail.smtp.ssl.trust", "*");
          props.put("mail.smtp.starttls.enable", "true");
          props.put("mail.smtp.ssl.socketFactory", "javax.net.ssl.SSLSocketFactory");

          MyAuth auth = new MyAuth();
          javax.mail.Session session = javax.mail.Session.getDefaultInstance(props, auth);
          MimeMessage msg = new MimeMessage(session);

          msg.setFrom(new InternetAddress("*****@*****.**"));
          msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
          msg.setSubject(subject);

          msg.setText(body);
          Transport.send(msg);
          request.setAttribute("msg", "Mail Sent Successfully on your registered E-mail ID.");
          request.getRequestDispatcher("/recover.jsp").forward(request, response);
        } catch (Exception e) {
          request.setAttribute("msg", "Mail cannot be sent.");
        }
      } else {
        request.setAttribute("msg", "Given Information is Wrong.");
      }
    } else {
      request.setAttribute("msg", "Given Information is Wrong.");
    }
    request.getRequestDispatcher("/recover.jsp").forward(request, response);
  }
Esempio n. 19
0
  static void email(String mail) {

    String to = mail; // change accordingly
    init();
    // Get the session object
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session;
    session =
        Session.getDefaultInstance(
            props,
            new javax.mail.Authenticator() {
              @Override
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                    "*****@*****.**", "onlinevoting"); // change accordingly
              }
            });

    // compose message
    try {
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress("*****@*****.**")); // change accordingly
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
      message.setSubject("VOTER_ID");
      boolean b1 = false;
      String voterid = null;
      String pass = null;
      x:
      while (rs.next()) {
        if (to.equalsIgnoreCase(rs.getString(8))) {
          b1 = true;
          voterid = rs.getString(1);
          pass = rs.getString(7);

          break x;
        }
      }
      if (b1 == true) {
        String msg = "Here is your voter id and password: "******" " + pass;
        message.setText(msg);

        // send message
        Transport.send(message);

        System.out.println("message sent successfully");
      }

    } catch (Exception e) {
      System.out.println("error in message sending:" + e);
    }
  }
Esempio n. 20
0
  @POST
  @Produces(value = MediaType.TEXT_PLAIN)
  public String sendEmail(
      @Context HttpServletRequest request, @Context HttpServletResponse response) {
    String result = "";
    // Recipient's email ID needs to be mentioned.
    String sender = request.getParameter("sender");
    String receiver = request.getParameter("receiver");
    String subject = request.getParameter("subject");
    String messageFromSender = request.getParameter("message");
    String smtp = request.getParameter("smtp");
    System.out.println("display" + sender + receiver + subject + messageFromSender + smtp);
    if (smtp != null
        && sender != null
        && receiver != null
        && subject != null
        && messageFromSender != null) {
      // Recipient's email ID needs to be mentioned.
      String to = receiver;

      // Sender's email ID needs to be mentioned
      String from = sender;

      // Assuming you are sending email from localhost
      String host = smtp; // "smtp.wlink.com.np";

      // 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(subject);
        // Now set the actual message
        message.setText(messageFromSender + "\n\nThis message was sent on :" + getDate());
        // Send message
        Transport.send(message);
        result = "Email Successfully sent";
      } catch (MessagingException mex) {
        mex.printStackTrace();
        result = "Error Occured. Please Try again";
      }
    }
    return result;
  }
 private void sendEmail(String subject, String body, String to) throws MessagingException {
   log.debug("Sending e-mail message to '" + to + "' with subject: " + subject);
   MimeMessage msg = new MimeMessage(session);
   msg.setFrom();
   msg.setRecipients(Message.RecipientType.TO, to);
   msg.setSubject(subject);
   msg.setSentDate(new Date());
   msg.setText(body);
   Transport.send(msg);
 }
Esempio n. 22
0
  public static MimeMessage createMessage(
      Session session,
      String subject,
      String html,
      String text,
      Address from,
      Address[] to,
      Attachment... attachments) {

    if (text == null) text = Html.convertHtmlToText(html);

    MimeMessage msg = createEmptyMimeMessage(session);
    try {
      msg.setSubject(subject, charset);
      msg.setFrom(from);
      msg.setRecipients(Message.RecipientType.TO, to);

      if ((attachments == null || attachments.length == 0)) {
        // no attachments

        if (Str.isBlank(html)) {
          // no html
          msg.setText(text, charset);
          return msg;
        }

        msg.setContent(createMultipartAlternative(text, html));
        return msg;
      }

      MimeMultipart multipartMixed = new MimeMultipart("mixed");

      if (Str.isBlank(html)) {
        // no html
        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText(text, charset);
        multipartMixed.addBodyPart(textBodyPart);
      } else {
        // html
        MimeBodyPart wrapAlternative = new MimeBodyPart();
        wrapAlternative.setContent(createMultipartAlternative(text, html));
        multipartMixed.addBodyPart(wrapAlternative);
      }

      for (Attachment attachment : attachments) {
        appendAttachment(multipartMixed, attachment);
      }

      msg.setContent(multipartMixed);
      return msg;

    } catch (MessagingException ex) {
      throw new RuntimeException(ex);
    }
  }
  private void sendEmail(User u) throws UnsupportedEncodingException {

    String uuid = UUID.randomUUID().toString();

    StringBuffer requestURL = request.getRequestURL();
    int li = requestURL.lastIndexOf("/");
    String url = requestURL.substring(0, li);
    url += "/" + "newPasswordForm?" + "uuid=" + uuid;

    u.setPassword(UUID.randomUUID().toString());
    u.setNewPasswordKey(uuid);
    ls.save(u);

    System.out.println(url);

    InternetAddress ToAddress =
        new InternetAddress(u.getEmail(), u.getUserName(), "ISO-2022-JP"); // 送信相手
    InternetAddress FromAddress =
        new InternetAddress("*****@*****.**", "崇城大学 和泉研究室", "ISO-2022-JP"); // 送信元(自分)

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    try {
      message.setFrom(FromAddress);
      message.addRecipient(Message.RecipientType.TO, ToAddress);
      message.setSubject("にわるかのパスワードをリセットしました", "ISO-2022-JP");

      StringBuilder sb = new StringBuilder();
      sb.append(u.getUserName() + "様\n");
      sb.append("\n");
      sb.append("にわるかをご利用いただきありがとうございます。\n");
      sb.append("\n");
      sb.append("パスワードをリセット致しましたので、次のURLをクリックして新しいパスワードを設定してください。\n");
      sb.append("\n");
      sb.append("---------------------------------------------------------------------\n");
      sb.append(url);
      sb.append("\n");
      sb.append("---------------------------------------------------------------------\n");
      sb.append("\n");
      sb.append("アカウントの情報は次の通りです\n");
      sb.append("にわるか ID:").append(" ").append(u.getName());
      sb.append("\n");
      sb.append("ユーザ名:").append(" ").append(u.getUserName());
      sb.append("\n\n");
      sb.append("----\n");
      sb.append("\"にわるか\"は崇城大学和泉研究室で開発されています\n");
      sb.append("http://sojotwitapps.appspot.com/\n");
      sb.append("http://www.cis.sojo-u.ac.jp/~izumi\n");
      message.setText(sb.toString(), "ISO-2022-JP");
      Transport.send(message);
    } catch (MessagingException e) {
      e.printStackTrace();
    }
  }
Esempio n. 24
0
 public void sendEmailUsingJava(String to, String content, String subjectContext) {
   // int smtpPort = 465;
   // int smtpPort = 587;
   // String smtpHost = "smtp.gmail.com";
   // int smtpPort = 25;
   // String smtpHost = "exsmtp.wvu.edu";
   String subject = constants.getString(subjectContext);
   int smtpPort = Integer.parseInt(constants.getString("smtpPort"));
   String smtpHost = constants.getString("smtpHost");
   String urPassword = constants.getString("password");
   String from = constants.getString("emailaddress");
   // String content = contentText;
   // Create a mail session
   java.util.Properties props = new java.util.Properties();
   props = System.getProperties();
   props.put("mail.smtp.host", smtpHost);
   // props.put("mail.smtp.starttls.enable", "true");
   props.put("mail.smtps.auth", "true");
   SmtpAuthenticator authentication = new SmtpAuthenticator();
   // Session session = Session.getInstance(props, null);
   Session session = Session.getInstance(props, authentication);
   session.setDebug(true);
   // Construct the message
   try {
     MimeMessage msg = new MimeMessage(session);
     msg.setFrom(new InternetAddress(from));
     msg.setRecipient(RecipientType.TO, new InternetAddress(to));
     msg.setSubject(subject);
     msg.setText(content);
     msg.setSentDate(new Date());
     Transport tr = null;
     tr = session.getTransport("smtp");
     tr.connect(smtpHost, smtpPort, from, urPassword);
     tr.sendMessage(msg, msg.getAllRecipients());
   } catch (AddressException e) {
     System.out.println(e.getClass().getName() + ": " + e.getMessage());
     Log.info(e.getClass().getName() + ": " + e.getMessage());
     StackTraceElement[] trace = e.getStackTrace();
     for (int i = 0; i < trace.length; i++) {
       System.out.println("\t" + trace[i].toString());
       Log.info("\n\t" + trace[i].toString());
     }
     e.printStackTrace();
   } catch (MessagingException e) {
     System.out.println(e.getClass().getName() + ": " + e.getMessage());
     Log.info(e.getClass().getName() + ": " + e.getMessage());
     StackTraceElement[] trace = e.getStackTrace();
     for (int i = 0; i < trace.length; i++) {
       System.out.println("\t" + trace[i].toString());
       Log.info("\n\t" + trace[i].toString());
     }
     e.printStackTrace();
   }
 }
Esempio n. 25
0
  public void send(String to, String text) throws MessagingException {
    // setup the message
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(text);

    // send message
    Transport.send(message);
    System.out.println("Message sent.");
  }
Esempio n. 26
0
  private MimeMessage createMimeMessage(Email email) throws AddressException, MessagingException {

    MimeMessage mail = mailSender.createMimeMessage();
    InternetAddress senderAddress = new InternetAddress(email.getFrom());
    mail.addRecipient(RecipientType.TO, new InternetAddress(email.getTo()));
    mail.setSender(senderAddress);
    mail.setFrom(senderAddress);
    mail.setText(email.getMessage());
    mail.setSubject(email.getSubject());
    mail.addHeader("Content-Type", "text/html; charset=UTF-8");

    return mail;
  }
Esempio n. 27
0
 public static MimeMessage createTextMessage(
     Session session, String subject, String text, Address from, Address[] to) {
   MimeMessage msg = createEmptyMimeMessage(session);
   try {
     msg.setSubject(subject, charset);
     msg.setText(text, charset);
     msg.setFrom(from);
     msg.setRecipients(Message.RecipientType.TO, to);
   } catch (MessagingException ex) {
     throw new RuntimeException(ex);
   }
   return msg;
 }
Esempio n. 28
0
  @Override
  public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
    to = (String) workItem.getParameter("To");
    from = (String) workItem.getParameter("From");
    subject = (String) workItem.getParameter("Subject");
    body = (String) workItem.getParameter("Body");

    System.out.println("====================================");
    System.out.println("Executing Email task: " + workItem);
    System.out.println("From: " + from);
    System.out.println("To: " + to);
    System.out.println("Subject: " + subject);
    System.out.println("Body: " + body);
    System.out.println("====================================");

    // Assuming you are sending email from localhost
    String host = "localhost";

    // 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(subject);

      // Now set the actual message
      message.setText(body);

      // Send message
      Transport.send(message);
      System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
      mex.printStackTrace();
    }
    manager.completeWorkItem(workItem.getId(), workItem.getResults());
  }
Esempio n. 29
0
 // sending the mail
 private boolean sendMail(String subject, String message) {
   MimeMessage msg = new MimeMessage(session);
   try {
     msg.setFrom(from);
     msg.setSubject(subject);
     msg.setText(message);
     msg.setRecipient(Message.RecipientType.TO, to);
     Transport.send(msg);
     return true;
   } catch (Exception e) {
     ConsoleUtils.printException(e, Core.NAME, "Can't send mail!");
     return false;
   }
 }
  protected void putMailInMailbox(final int messages) throws MessagingException {

    for (int i = 0; i < messages; i++) {
      final MimeMessage message = new MimeMessage((Session) null);
      message.setFrom(new InternetAddress(EMAIL_TO));
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
      message.setSubject(EMAIL_SUBJECT + "::" + i);
      message.setText(EMAIL_TEXT + "::" + SID++);
      message.setSentDate(new Date());
      MockMailbox.get(EMAIL_USER_ADDRESS).getInbox().add(message);
    }

    logger.info("Putted " + messages + " into mailbox");
  }