Example #1
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));
    }
  }
  /**
   * Initialize this plugin. This method only called when the plugin is instantiated.
   *
   * @param servletConfig Servlet config object for the plugin to retrieve any initialization
   *     parameters
   * @param blojsomConfiguration {@link org.blojsom.blog.BlojsomConfiguration} information
   * @throws BlojsomPluginException If there is an error initializing the plugin
   */
  public void init(ServletConfig servletConfig, BlojsomConfiguration blojsomConfiguration)
      throws BlojsomPluginException {
    String hostname = servletConfig.getInitParameter(SMTPSERVER_IP);

    if (hostname != null) {
      if (hostname.startsWith("java:comp/env")) {
        try {
          Context context = new InitialContext();
          _mailsession = (Session) context.lookup(hostname);
        } catch (NamingException e) {
          _logger.error(e);
          throw new BlojsomPluginException(e);
        }
      } else {
        String username = servletConfig.getInitParameter(SMTPSERVER_USERNAME_IP);
        String password = servletConfig.getInitParameter(SMTPSERVER_PASSWORD_IP);

        Properties props = new Properties();
        props.put(SESSION_NAME, hostname);
        if (BlojsomUtils.checkNullOrBlank(username) || BlojsomUtils.checkNullOrBlank(password)) {
          _mailsession = Session.getDefaultInstance(props, null);
        } else {
          _mailsession =
              Session.getDefaultInstance(props, new SimpleAuthenticator(username, password));
        }
      }
    }
  }
Example #3
0
  /**
   * Send an email to an address, supplying the recipient, subject and body.
   *
   * @param to the address to send to
   * @param subject The Subject of the email
   * @param body The content of the email
   * @param from the address to send from
   * @param webProperties Common properties for all emails (such as from, authentication)
   * @throws MessagingException if there is a problem creating the email
   */
  public static void email(
      String to, String subject, String body, String from, final Map webProperties)
      throws MessagingException {
    final String user = (String) webProperties.get("mail.smtp.user");
    String smtpPort = (String) webProperties.get("mail.smtp.port");
    String authFlag = (String) webProperties.get("mail.smtp.auth");
    String starttlsFlag = (String) webProperties.get("mail.smtp.starttls.enable");

    Properties properties = System.getProperties();

    properties.put("mail.smtp.host", webProperties.get("mail.host"));
    properties.put("mail.smtp.user", user);
    // Fix to "javax.mail.MessagingException: 501 Syntactically
    // invalid HELO argument(s)" problem
    // See http://forum.java.sun.com/thread.jspa?threadID=487000&messageID=2280968
    properties.put("mail.smtp.localhost", "localhost");
    if (smtpPort != null) {
      properties.put("mail.smtp.port", smtpPort);
    }

    if (starttlsFlag != null) {
      properties.put("mail.smtp.starttls.enable", starttlsFlag);
    }
    if (authFlag != null) {
      properties.put("mail.smtp.auth", authFlag);
    }

    Session session;
    if (authFlag != null && ("true".equals(authFlag) || "t".equals(authFlag))) {
      Authenticator authenticator =
          new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
              String password = (String) webProperties.get("mail.server.password");
              return new PasswordAuthentication(user, password);
            }
          };
      session = Session.getDefaultInstance(properties, authenticator);
    } else {
      session = Session.getDefaultInstance(properties);
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, InternetAddress.parse(to, true)[0]);
    message.setSubject(subject);
    message.setContent(body, "text/plain");
    Transport.send(message);
  }
Example #4
0
  /**
   * Generate a MimeMessage with the specified attributes
   *
   * @param destEmailAddr The destination email address
   * @param fromEmailAddr The sender email address
   * @param fromName The senders display name
   * @param emailSubject The subject
   * @param emailPlainText The message body (plaintext)
   * @return The MimeMessage object
   * @throws Exception
   */
  public static MimeMessage generateMail(
      String destEmailAddr,
      String destPersonalName,
      String fromEmailAddr,
      String fromName,
      String emailSubject,
      String emailPlainText)
      throws Exception {

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null));

    InternetAddress[] toAddrs = InternetAddress.parse(destEmailAddr, false);
    if (destPersonalName != null) {
      toAddrs[0].setPersonal(destPersonalName);
    }
    InternetAddress from = new InternetAddress(fromEmailAddr);
    from.setPersonal(fromName);

    message.setRecipients(Message.RecipientType.TO, toAddrs);
    message.setFrom(from);
    message.setSubject(emailSubject);
    message.setSentDate(new java.util.Date());

    MimeMultipart msgbody = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setDataHandler(new DataHandler(new MailDataSource(emailPlainText, "text/plain")));
    msgbody.addBodyPart(html);
    message.setContent(msgbody);

    return message;
  }
Example #5
0
  public static void sendConfirmationRegisterMail(String mail, String name)
      throws UnsupportedEncodingException, MessagingException {
    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.getDefaultInstance(
            props,
            new javax.mail.Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM_ADDRESS, PASSWORD);
              }
            });

    String msgBody = "The staff wish you enjoy the contest!";

    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(FROM_ADDRESS, FROM_NAME));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mail, name));
    msg.setSubject("Welcome to pContest!");
    msg.setText(msgBody);
    Transport.send(msg);
  }
  @Override
  public void send(MimeMessage message) throws MailerException {
    Session session = Session.getDefaultInstance(getConfiguration());

    if (this.from != null) {
      try {
        message.setFrom(from);
      } catch (MessagingException e) {
        throw new MailerException(e);
      }
    }

    try {
      Transport tr = session.getTransport("smtp");
      if (getConfigurationProperty(Configuration.SMTP.AUTH, "true").equalsIgnoreCase("true")) {
        tr.connect(
            getConfigurationProperty(Configuration.SMTP.USER),
            getConfigurationProperty(Configuration.SMTP.PASSWORD));
      } else {
        tr.connect();
      }
      tr.sendMessage(message, message.getAllRecipients());
      tr.close();
    } catch (MessagingException e) {
      throw new MailerException(e);
    }
  }
  public boolean send() {
    try {
      Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
      Properties props = new Properties();
      props.setProperty("mail.transport.protocol", "smtp");
      props.setProperty("mail.host", "smtp.gmail.com");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");
      props.put("mail.debug", "true");
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.socketFactory.fallback", "false");
      Session session = Session.getDefaultInstance(props, new GJMailAuthenticator());
      session.setDebug(true);
      Transport transport = session.getTransport();
      InternetAddress addressFrom = new InternetAddress("*****@*****.**");
      MimeMessage message = new MimeMessage(session);
      message.setSender(addressFrom);
      message.setSubject(subject);
      message.setContent(text, "text/html");
      InternetAddress addressTo = new InternetAddress(to);
      message.setRecipient(Message.RecipientType.TO, addressTo);
      transport.connect();
      Transport.send(message);
      transport.close();
      System.out.println("DONE");

    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

    return true;
  }
Example #8
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();
    }
  }
  public void testMimeMultipartBinaryParserGetMimeContent() throws Exception {
    MimeBodyPart m = createMultipartMessage();

    List certList = new ArrayList();

    certList.add(_signCert);
    certList.add(_origCert);

    Store certs = new JcaCertStore(certList);

    ASN1EncodableVector signedAttrs = generateSignedAttributes();

    SMIMESignedGenerator gen = new SMIMESignedGenerator("binary");

    gen.addSignerInfoGenerator(
        new JcaSimpleSignerInfoGeneratorBuilder()
            .setProvider(BC)
            .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
            .build("SHA1withRSA", _signKP.getPrivate(), _signCert));
    gen.addCertificates(certs);

    MimeMultipart mm = gen.generate(m);

    SMIMESignedParser s =
        new SMIMESignedParser(
            new JcaDigestCalculatorProviderBuilder().setProvider(BC).build(), mm, "binary");

    verifySigners(s.getCertificates(), s.getSignerInfos());

    MimeMessage bp = s.getContentAsMimeMessage(Session.getDefaultInstance(new Properties()));
  }
Example #10
0
  public static void sendEmail(
      InternetAddress from, InternetAddress to, String content, String requester)
      throws MessagingException, UnsupportedEncodingException {

    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", SMTP_HOST_NAME);
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject("MN Traffic Generation is used by " + requester);
    message.setContent(content, "text/plain");

    message.addRecipient(Message.RecipientType.TO, to);

    InternetAddress[] replyto = new InternetAddress[1];
    replyto[0] = from;

    message.setFrom(from);
    message.setReplyTo(replyto);
    message.setSender(from);

    transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));

    transport.close();
  }
  public static void leaveDeclinedMail(String email, String employeeId) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String msgBody =
        "Dear Employee"
            + "This letter is in response to your request for a leave of absence beginning"
            + " through   Although we make every effort"
            + " to accommodate employees with a need for time off, unfortunately,"
            + " your leave request is not approved due to Project deadLine to complete"
            + "If you feel that this decision is made in error or that extenuating circumstances warrant"
            + "further review of your request, please feel free to contact me with more information or"
            + "additional details surrounding your need for leave."
            + "Regards,\n"
            + "  HR  ";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "HR Manager"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, "Hi prodigy"));
      msg.setSubject("Leave Request Declined");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (Exception e) {

    }
  }
  public static void leaveApprovedMail(
      String employeeName, String fromDate, String toDate, String email) {

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

    String msgBody =
        "Hi "
            + employeeName.toUpperCase()
            + "In response to your request for leave on date from "
            + fromDate
            + " to "
            + toDate
            + " \n"
            + "the management pleased to inform you that your leave request is approved.\n"
            + "Also, do delegate your daily work responsibilities to your assistants\n"
            + "and subordinates well to ensure a smooth flow of operation in your absence.\n"
            + "For your information, with these approved  days of leave,\n"
            + "We wish you a good rest on your off days.\n"
            + "Regards,\n"
            + "  HR  ";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "HR Manager"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, employeeName));
      msg.setSubject("Leave Request Approved");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (Exception e) {

    }
  }
  public static void passwordResetLinkMail(String email) {
    System.out.println("in password reset link");
    System.out.println("email is " + email);
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String msgBody =
        "Dear Employee"
            + "As your request we've sent you a password reset link\n"
            + "Past this link to address-bar or click on this link to reset your password\n"
            + "Link is [http://prodigy-software.appspot.com/passwordResetLink]"
            + "\n"
            + "Regards,\n"
            + "  HR  ";

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "HR Manager"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, "Hi prodigy"));
      msg.setSubject("Password Reset Link");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (Exception e) {

    }
  }
Example #14
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
  public static void main(String[] args) throws MessagingException, IOException {
    IMAPFolder folder = null;
    Store store = null;
    String subject = null;
    Flag flag = null;
    try {
      Properties props = System.getProperties();
      props.setProperty("mail.store.protocol", "imaps");
      props.setProperty("mail.imap.host", "imap.googlemail.com");
      SimpleAuthenticator authenticator =
          new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy");
      Session session = Session.getDefaultInstance(props, null);
      // Session session = Session.getDefaultInstance(props, authenticator);

      store = session.getStore("imaps");
      //          store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");
      // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy");

      store.connect("*****@*****.**", "hhy8611hhy");
      // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email
      // account
      folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account

      if (!folder.isOpen()) folder.open(Folder.READ_WRITE);
      Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages();
      System.out.println("No of get Messages : " + messages.length);
      System.out.println("No of Messages : " + folder.getMessageCount());
      System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
      System.out.println("No of New Messages : " + folder.getNewMessageCount());
      System.out.println(messages.length);
      for (int i = 0; i < messages.length; i++) {

        System.out.println(
            "*****************************************************************************");
        System.out.println("MESSAGE " + (i + 1) + ":");
        Message msg = messages[i];
        // System.out.println(msg.getMessageNumber());
        // Object String;
        // System.out.println(folder.getUID(msg)

        subject = msg.getSubject();

        System.out.println("Subject: " + subject);
        System.out.println("From: " + msg.getFrom()[0]);
        System.out.println("To: " + msg.getAllRecipients()[0]);
        System.out.println("Date: " + msg.getReceivedDate());
        System.out.println("Size: " + msg.getSize());
        System.out.println(msg.getFlags());
        System.out.println("Body: \n" + msg.getContent());
        System.out.println(msg.getContentType());
      }
    } finally {
      if (folder != null && folder.isOpen()) {
        folder.close(true);
      }
      if (store != null) {
        store.close();
      }
    }
  }
Example #16
0
  /**
   * Sends an email using the given parameters.
   *
   * @param smtp The SMTP server to send from
   * @param from The from-address
   * @param to The to-address
   * @param subj The subject line
   * @param body The message body
   * @throws MessagingException If the email fails to send
   */
  public static void send(
      final String smtp, final String from, final String to, final String subj, final String body)
      throws MessagingException {
    // Silently quit if we are missing any required email information
    if (smtp == null
        || from == null
        || to == null
        || smtp.isEmpty()
        || from.isEmpty()
        || to.isEmpty()) return;

    // Set the host smtp address
    final Properties mailProps = new Properties();
    mailProps.put("mail.smtp.host", smtp);

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

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

    // set the from and to address
    final InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    final InternetAddress addressTo = new InternetAddress(to);
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    // set the subject and body
    msg.setSubject(subj);
    msg.setContent(body, "text/plain");

    // send the email message
    Transport.send(msg);
  }
Example #17
0
 private void loadSettings(File dataFolder) {
   File configFile = new File(dataFolder, "mailConfig.yml");
   try {
     YamlConfiguration config = new YamlConfiguration();
     config.load(configFile);
     // Standardized Properties to talk with SMTP Server
     Properties properties = System.getProperties();
     // HOST
     properties.setProperty("mail.smtp.host", config.getString("smtp.host"));
     // PORT
     properties.setProperty("mail.smtp.port", config.getString("smtp.port"));
     // Has an Authentifaction
     properties.setProperty("mail.smtp.auth", "true");
     // Create session
     session =
         Session.getDefaultInstance(
             properties,
             new MailAuthenticator(
                 config.getString("smtp.username"), config.getString("smtp.password")));
     // Get Addresses
     from = new InternetAddress(config.getString("smtp.from"));
     to = new InternetAddress(config.getString("smtp.to"));
   } catch (Exception e) {
     ConsoleUtils.printException(e, Core.NAME, "Can't initiate E-Mail settings!");
   }
 }
Example #18
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);
    }
  }
Example #19
0
  public void send(String subject, String text, String fromEmail, String toEmail) {
    Session session =
        Session.getDefaultInstance(
            props,
            new Authenticator() {
              protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
              }
            });

    try {
      Message message = new MimeMessage(session);
      // от кого
      message.setFrom(new InternetAddress(username));
      // кому
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
      // тема сообщения
      message.setSubject(subject);
      // текст
      message.setText(text);

      // отправляем сообщение
      Transport.send(message);
    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }
Example #20
0
  /**
   * Este método é responsável por enviar email.
   *
   * @param pServidorSMTP
   * @param pDe
   * @param pPara
   * @param pCopia
   * @param pBcc
   * @param pAssunto
   * @param pTexto
   * @return true se o email for enviado, false caso contrário.
   */
  public static boolean enviarEmail(
      final String pServidorSMTP,
      final String pDe,
      final String pPara,
      final String pCopia,
      final String pBcc,
      final String pAssunto,
      final String pTexto) {

    Properties mailPprops = new Properties();
    mailPprops.put("mail.smtp.host", pServidorSMTP);

    Session mailSession = Session.getDefaultInstance(mailPprops, null);

    try {
      // Mudança: Aplicação usa ";", componente usa ","
      String para = pPara.replaceAll(";", ",");

      // Criando a mensagem
      MimeMessage msg = new MimeMessage(mailSession);
      // Atribuir rementente
      msg.setFrom(new InternetAddress(pDe));
      // Atribuir destinatários
      InternetAddress[] endereco = null;
      // Para
      if ((para != null) && (!para.equals(""))) {
        endereco = InternetAddress.parse(para);
        msg.setRecipients(Message.RecipientType.TO, endereco);
      }
      // Cc
      if ((pCopia != null) && (!pCopia.equals(""))) {
        endereco = InternetAddress.parse(pCopia);
        msg.setRecipients(Message.RecipientType.CC, endereco);
      }
      // Bcc
      if ((pBcc != null) && (!pBcc.equals(""))) {
        endereco = InternetAddress.parse(pBcc);
        msg.setRecipients(Message.RecipientType.BCC, endereco);
      }

      // Atribuir assunto
      msg.setSubject(pAssunto);

      // Atribuir corpo do email (texto)
      if (pTexto != null) msg.setContent(pTexto, "text/html");

      msg.setSentDate(new Date());

      Transport.send(msg);

      msg = null;
      mailSession = null;
    } catch (MessagingException mex) {
      if (Constants.DEBUG) {
        mex.printStackTrace(System.out);
      }
      return false;
    }
    return true;
  }
  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);
  }
Example #22
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();
    }
  }
Example #23
0
  public boolean send() {

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");

    Session mailSession = Session.getDefaultInstance(props);
    Message simpleMessage = new MimeMessage(mailSession);

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
      fromAddress = new InternetAddress(from);
      toAddress = new InternetAddress(to);
    } catch (AddressException e) {
      e.printStackTrace();
      return false;
    }

    try {
      simpleMessage.setFrom(fromAddress);
      simpleMessage.setRecipient(RecipientType.TO, toAddress);
      simpleMessage.setSubject(subject);
      simpleMessage.setText(text);

      Transport.send(simpleMessage);
      return true;
    } catch (MessagingException e) {
      e.printStackTrace();
      return false;
    }
  }
Example #24
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();
    }
  }
Example #25
0
  public void test() throws Exception {

    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", SMTP_HOST_NAME);
    props.put("mail.smtps.auth", "true");
    props.put("mail.smtps.quitwait", "false");
    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(true);

    Transport transport = mailSession.getTransport();
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress(username.getText()));
    message.setSubject(subject.getText());

    String s = msgfield.getText();
    message.setContent(s, "text/plain");
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailID.getText()));
    System.out.println("8i m here ");
    try {
      transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, username.getText(), password.getText());
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, "invalid username or password");
    }
    System.out.println("8i m here also yaar");
    // transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
    transport.sendMessage(message123, message123.getAllRecipients());
    transport.close();
    System.out.println(s);
  }
  public void enviarEmail() {
    FacesContext context = FacesContext.getCurrentInstance();
    AutenticaUsuario autenticaUsuario =
        new AutenticaUsuario(GmailBean.CONTA_GMAIL, GmailBean.SENHA_GMAIL);
    Session session = Session.getDefaultInstance(this.configuracaoEmail(), autenticaUsuario);
    session.setDebug(true);

    try {

      Transport envio = null;
      MimeMessage email = new MimeMessage(session);
      email.setRecipient(Message.RecipientType.TO, new InternetAddress(this.para));
      email.setFrom(new InternetAddress(this.de));
      email.setSubject(this.assunto);
      email.setContent(this.mensagem, "text/plain");
      email.setSentDate(new Date());
      envio = session.getTransport("smtp");
      envio.connect(GmailBean.SERVIDOR_SMTP, GmailBean.CONTA_GMAIL, GmailBean.SENHA_GMAIL);
      email.saveChanges();
      envio.sendMessage(email, email.getAllRecipients());
      envio.close();

      context.addMessage(null, new FacesMessage("E-mail enviado com sucesso"));

    } catch (AddressException e) {
      FacesMessage msg =
          new FacesMessage("Erro ao montar mensagem de e-mail! Erro: " + e.getMessage());
      context.addMessage(null, msg);
      return;
    } catch (MessagingException e) {
      FacesMessage msg = new FacesMessage("Erro ao enviar e-mail! Erro: " + e.getMessage());
      context.addMessage(null, msg);
      return;
    }
  }
 /**
  * 以文本格式发送邮件
  *
  * @param mailInfo 待发送的邮件信息
  */
 public static boolean sendTextMail(MailSenderInfo mailInfo) {
   // 判断是否需要身份认证
   MailAuthenticator authenticator = null;
   Properties pro = mailInfo.getProperties();
   if (mailInfo.isValidate()) {
     // 如果需要身份认证,则创建一个密码验证器
     authenticator = new MailAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
   }
   // 根据邮件会话属性和密码验证器构造一个发送邮件的session
   Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
   try {
     // 根据session创建一个邮件消息
     Message mailMessage = new MimeMessage(sendMailSession);
     // 创建邮件发送者地址
     Address from = new InternetAddress(mailInfo.getFromAddress());
     // 设置邮件消息的发送者
     mailMessage.setFrom(from);
     // 创建邮件的接收者地址,并设置到邮件消息中
     Address to = new InternetAddress(mailInfo.getToAddress());
     mailMessage.setRecipient(Message.RecipientType.TO, to);
     // 设置邮件消息的主题
     mailMessage.setSubject(mailInfo.getSubject());
     // 设置邮件消息发送的时间
     mailMessage.setSentDate(new Date());
     // 设置邮件消息的主要内容
     String mailContent = mailInfo.getContent();
     mailMessage.setText(mailContent);
     // 发送邮件
     Transport.send(mailMessage);
     return true;
   } catch (MessagingException ex) {
     ex.printStackTrace();
   }
   return false;
 }
Example #28
0
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp) {
    Datastore.instance().startRequest();
    try {
      MimeMessage mime = null;
      try {
        mime =
            new MimeMessage(
                Session.getDefaultInstance(new Properties(), null), req.getInputStream());
      } catch (Exception e) {
        LOG.log(Level.SEVERE, "error while parsing incoming email", e);
        return;
      }

      EmailMessage email = parseToBetterFormat(mime);
      if (email == null) {
        // parseToBetterFormat already logged why the email couldn't be parsed
        return;
      }

      for (InternetAddress ia : email.to) {
        Message msg = extractPchappMessageFromEmail(email, ia);
        if (msg != null) {
          Command.getCommandHandler(msg).doCommand(msg);
          msg.user.maybeMarkAsSeen();
        }
      }
    } finally {
      Datastore.instance().endRequest();
    }
  }
  public static void main(String args[]) throws Exception {
    //
    // create the generator for creating an smime/compressed message
    //
    SMIMECompressedGenerator gen = new SMIMECompressedGenerator();

    //
    // create the base for our message
    //
    MimeBodyPart msg = new MimeBodyPart();

    msg.setText("Hello world!");

    MimeBodyPart mp = gen.generate(msg, new ZlibCompressor());

    //
    // Get a Session object and create the mail message
    //
    Properties props = System.getProperties();
    Session session = Session.getDefaultInstance(props, null);

    Address fromUser = new InternetAddress("\"Eric H. Echidna\"<*****@*****.**>");
    Address toUser = new InternetAddress("*****@*****.**");

    MimeMessage body = new MimeMessage(session);
    body.setFrom(fromUser);
    body.setRecipient(Message.RecipientType.TO, toUser);
    body.setSubject("example compressed message");
    body.setContent(mp.getContent(), mp.getContentType());
    body.saveChanges();

    body.writeTo(new FileOutputStream("compressed.message"));
  }
Example #30
0
  public void sendMail(String id, String mail) {
    System.out.println("In de send mail method");
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    String msgBody =
        "Dear Beta-SMS user,\n Thank you for submiting a feature/issue request. You can follow the status at http://beta-sms.coralic.nl?TABTOSELECT=tab-todo&ID="
            + id
            + "\n \n Thank you for using Beta-SMS.";

    try {
      System.out.println("Building the email and trying to send it");
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress("*****@*****.**", "beta-sms.coralic.nl Beta-SMS"));
      msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mail, mail));
      msg.setSubject("Beta-SMS feature/issue request processed.");
      msg.setText(msgBody);
      Transport.send(msg);

    } catch (AddressException e) {
      System.err.println(e.getMessage());
    } catch (MessagingException e) {
      System.err.println(e.getMessage());
    } catch (UnsupportedEncodingException e) {
      System.err.println(e.getMessage());
    }
  }