Example usage for javax.mail Message setSubject

List of usage examples for javax.mail Message setSubject

Introduction

In this page you can find the example usage for javax.mail Message setSubject.

Prototype

public abstract void setSubject(String subject) throws MessagingException;

Source Link

Document

Set the subject of this message.

Usage

From source file:mail.MailService.java

/**
 * Erstellt eine MIME-Mail.//from  ww  w. j a v a 2s.  c  om
 * @param email
 * @throws MessagingException
 * @throws IOException
 */
public String createMail1(Mail email, Config config) throws MessagingException, IOException {

    Properties props = new Properties();
    props.put("mail.smtp.host", "mail.java-tutor.com");
    Session session = Session.getDefaultInstance(props);

    Message msg = new MimeMessage(session);
    //      msg.setHeader("MIME-Version" , "1.0"); 
    //      msg.setHeader("Content-Type" , "text/plain"); 

    // Absender
    InternetAddress addressFrom = new InternetAddress(email.getAbsender());
    msg.setFrom(addressFrom);

    // Empfnger
    InternetAddress addressTo = new InternetAddress(email.getEmpfaenger());
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    msg.setSubject(email.getBetreff());
    msg.setSentDate(email.getAbsendeDatum());
    String txt = Utils.toString(email.getText());

    msg.setText(txt);
    msg.saveChanges();

    // Mail in Ausgabestrom schreiben
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        msg.writeTo(bOut);
    } catch (IOException e) {
        if (config.isTest())
            System.out.println("Fehler beim Schreiben der Mail in Schritt 1");
        throw e;
    }
    return removeMessageId(bOut.toString(Charset.defaultCharset().name()));
}

From source file:it.cnr.icar.eric.server.event.EmailNotifier.java

private void postMail(String endpoint, String message, String subject, String contentType)
        throws MessagingException {

    // get the SMTP address
    String smtpHost = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.host");

    // get the FROM address
    String fromAddress = RegistryProperties.getInstance()
            .getProperty("eric.server.event.EmailNotifier.smtp.from", "eric@localhost");

    // get the TO address that follows 'mailto:'
    String recipient = endpoint.substring(7);

    String smtpPort = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.port",
            null);//from   w  ww .  j  ava  2s . c  om

    String smtpAuth = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.auth",
            null);

    String smtpDebug = RegistryProperties.getInstance()
            .getProperty("eric.server.event.EmailNotifier.smtp.debug", "false");

    //Set the host smtp address
    Properties props = new Properties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.debug", smtpDebug);
    props.put("mail.smtp.host", smtpHost);
    if ((smtpPort != null) && (smtpPort.length() > 0)) {
        props.put("mail.smtp.port", smtpPort);
    }
    Session session;
    if ("tls".equals(smtpAuth)) {
        // get the username
        String userName = RegistryProperties.getInstance()
                .getProperty("eric.server.event.EmailNotifier.smtp.user", null);

        String password = RegistryProperties.getInstance()
                .getProperty("eric.server.event.EmailNotifier.smtp.password", null);

        Authenticator authenticator = new MyAuthenticator(userName, password);
        props.put("mail.user", userName);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        session = Session.getInstance(props, authenticator);
    } else {
        session = Session.getInstance(props);
    }

    session.setDebug(Boolean.valueOf(smtpDebug).booleanValue());

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

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

    InternetAddress[] addressTo = new InternetAddress[1];
    addressTo[0] = new InternetAddress(recipient);
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, contentType);
    Transport.send(msg);
}

From source file:mail.MailService.java

/**
 * Erstellt eine kanonisierte MIME-Mail.
 * @param email//  www  .j a  v  a 2 s  .  c  o m
 * @throws MessagingException
 * @throws IOException
 */
public String createMail2(Mail email, Config config) throws MessagingException, IOException {

    byte[] mailAsBytes = email.getText();
    int laenge = mailAsBytes.length + getCRLF().length;
    byte[] bOout = new byte[laenge];
    for (int i = 0; i < mailAsBytes.length; i++) {
        bOout[i] = mailAsBytes[i];
    }

    byte[] neu = getCRLF();
    int counter = 0;
    for (int i = mailAsBytes.length; i < laenge; i++) {
        bOout[i] = neu[counter];
        counter++;
    }

    email.setText(bOout);

    Properties props = new Properties();
    props.put("mail.smtp.host", "mail.java-tutor.com");
    Session session = Session.getDefaultInstance(props);

    Message msg = new MimeMessage(session);
    //      msg.setHeader("MIME-Version" , "1.0"); 
    //      msg.setHeader("Content-Type" , "text/plain"); 

    // Absender
    InternetAddress addressFrom = new InternetAddress(email.getAbsender());
    msg.setFrom(addressFrom);

    // Empfnger
    InternetAddress addressTo = new InternetAddress(email.getEmpfaenger());
    msg.setRecipient(Message.RecipientType.TO, addressTo);

    msg.setSubject(email.getBetreff());
    msg.setSentDate(email.getAbsendeDatum());

    msg.setText(Utils.toString(email.getText()));
    msg.saveChanges();
    /*       
           // Erstellen des Content
           MimeMultipart content = new MimeMultipart("text"); 
                  
           MimeBodyPart part = new MimeBodyPart(); 
           part.setText(email.getText()); 
           part.setHeader("MIME-Version" , "1.0"); 
           part.setHeader("Content-Type" , part.getContentType()); 
                   
           content.addBodyPart(part);
           System.out.println(content.getContentType());
                  
          Message msg = new MimeMessage(session); 
          msg.setContent(content); 
          msg.setHeader("MIME-Version" , "1.0"); 
          msg.setHeader("Content-Type" , content.getContentType()); 
            
          InternetAddress addressFrom = new InternetAddress(email.getAbsender()); 
           msg.setFrom(addressFrom); 
                   
           InternetAddress addressTo = new InternetAddress(email.getEmpfnger()); 
           msg.setRecipient(Message.RecipientType.TO, addressTo); 
                   
           msg.setSubject(email.getBetreff());
           msg.setSentDate(email.getAbsendeDatum()); */

    //msg.setContent(email.getText(), "text/plain");

    // Mail in Ausgabestrom schreiben
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
        msg.writeTo(bOut);
    } catch (IOException e) {
        System.out.println("Fehler beim Schreiben der Mail in Schritt 2");
        throw e;
    }
    //      String out = bOut.toString();
    //       int pos1 = out.indexOf("Message-ID");
    //       int pos2 = out.indexOf("@localhost") + 13;
    //       String output = out.subSequence(0, pos1).toString();
    //       output += (out.substring(pos2));

    return removeMessageId(bOut.toString(Charset.defaultCharset().name()));
}

From source file:sendhtml.java

public sendhtml(String[] argv) {

    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;//from www .j av a 2  s .c  om
    String mailer = "sendhtml";
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    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("-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")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = 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.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]");
            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();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, 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);

        collect(in, msg);

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

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

        System.out.println("\nMail 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) {
        e.printStackTrace();
    }
}

From source file:sendhtml.java

public sendhtml(String[] argv) {

    String to, subject = null, from = null, cc = null, bcc = null, url = null;
    String mailhost = null;/*from   w  w w. ja  v  a2 s .  c om*/
    String mailer = "sendhtml";
    String protocol = null, host = null, user = null, password = null;
    String record = null; // name of folder in which to record mail
    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("-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")) {
            record = argv[++optind];
        } else if (argv[optind].equals("-s")) {
            subject = argv[++optind];
        } else if (argv[optind].equals("-o")) { // originator
            from = 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.out.println("Usage: sendhtml [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]");
            System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]");
            System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [address]");
            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();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, 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);

        collect(in, msg);

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

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

        System.out.println("\nMail 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) {
        e.printStackTrace();
    }
}

From source file:com.intuit.tank.mail.TankMailer.java

/**
 * @{inheritDoc/*w ww  .j  a va  2s  . c o m*/
 */
@Override
public void sendMail(MailMessage message, String... emailAddresses) {
    MailConfig mailConfig = new TankConfig().getMailConfig();
    Properties props = new Properties();
    props.put("mail.smtp.host", mailConfig.getSmtpHost());
    props.put("mail.smtp.port", mailConfig.getSmtpPort());

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

    InternetAddress fromAddress = null;
    InternetAddress toAddress = null;
    try {
        fromAddress = new InternetAddress(mailConfig.getMailFrom());
        simpleMessage.setFrom(fromAddress);
        for (String email : emailAddresses) {
            try {
                toAddress = new InternetAddress(email);
                simpleMessage.addRecipient(RecipientType.TO, toAddress);
            } catch (AddressException e) {
                LOG.warn("Error with recipient " + email + ": " + e.toString());
            }
        }

        simpleMessage.setSubject(message.getSubject());
        final MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(message.getPlainTextBody(), "text/plain");
        textPart.setHeader("MIME-Version", "1.0");
        textPart.setHeader("Content-Type", textPart.getContentType());
        // HTML version
        final MimeBodyPart htmlPart = new MimeBodyPart();
        // htmlPart.setContent(message.getHtmlBody(), "text/html");
        htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody())));
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html");
        // Create the Multipart. Add BodyParts to it.
        final Multipart mp = new MimeMultipart("alternative");
        mp.addBodyPart(textPart);
        mp.addBodyPart(htmlPart);
        // Set Multipart as the message's content
        simpleMessage.setContent(mp);
        simpleMessage.setHeader("MIME-Version", "1.0");
        simpleMessage.setHeader("Content-Type", mp.getContentType());
        logMsg(mailConfig.getSmtpHost(), simpleMessage);
        if (simpleMessage.getRecipients(RecipientType.TO) != null
                && simpleMessage.getRecipients(RecipientType.TO).length > 0) {
            Transport.send(simpleMessage);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:contestWebsite.Registration.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity contestInfo = Retrieve.contestInfo();

    Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap());
    for (Entry<String, String[]> param : params.entrySet()) {
        if (!"studentData".equals(param.getKey())) {
            params.put(param.getKey(), new String[] { escapeHtml4(param.getValue()[0]) });
        }/*w w  w .  j a  va2  s  .co m*/
    }

    String registrationType = params.get("registrationType")[0];
    String account = "no";
    if (params.containsKey("account")) {
        account = "yes";
    }
    String email = params.containsKey("email") && params.get("email")[0].length() > 0
            ? params.get("email")[0].toLowerCase().trim()
            : null;
    String schoolLevel = params.get("schoolLevel")[0];
    String schoolName = params.get("schoolName")[0].trim();
    String name = params.get("name")[0].trim();
    String classification = params.containsKey("classification") ? params.get("classification")[0] : "";
    String studentData = req.getParameter("studentData");
    String password = null;
    String confPassword = null;

    UserCookie userCookie = UserCookie.getCookie(req);
    boolean loggedIn = userCookie != null && userCookie.authenticate();
    if ((!loggedIn || !userCookie.isAdmin()) && email == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "E-Mail Address parameter ('email') must be specified");
        return;
    }

    HttpSession sess = req.getSession(true);
    sess.setAttribute("registrationType", registrationType);
    sess.setAttribute("account", account);
    sess.setAttribute("account", account);
    sess.setAttribute("name", name);
    sess.setAttribute("classification", classification);
    sess.setAttribute("schoolName", schoolName);
    sess.setAttribute("schoolLevel", schoolLevel);
    sess.setAttribute("email", email);
    sess.setAttribute("studentData", studentData);

    boolean reCaptchaResponse = false;
    if (!(Boolean) sess.getAttribute("nocaptcha")) {
        URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify");
        String charset = java.nio.charset.StandardCharsets.UTF_8.name();
        String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s",
                URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset),
                URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset),
                URLEncoder.encode(req.getRemoteAddr(), charset));

        final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                return connection.getInputStream();
            }
        }, Charsets.UTF_8));

        try {
            JSONObject JSONResponse = new JSONObject(response);
            reCaptchaResponse = JSONResponse.getBoolean("success");
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendRedirect("/contactUs?captchaError=1");
            return;
        }
    }

    if (!(Boolean) sess.getAttribute("nocaptcha") && !reCaptchaResponse) {
        resp.sendRedirect("/registration?captchaError=1");
    } else {
        if (account.equals("yes")) {
            password = params.get("password")[0];
            confPassword = params.get("confPassword")[0];
        }

        Query query = new Query("registration")
                .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, email)).setKeysOnly();
        List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));

        if (users.size() != 0 && email != null || account.equals("yes") && !confPassword.equals(password)) {
            if (users.size() != 0) {
                resp.sendRedirect("/registration?userError=1");
            } else if (!params.get("confPassword")[0].equals(params.get("password")[0])) {
                resp.sendRedirect("/registration?passwordError=1");
            } else {
                resp.sendRedirect("/registration?updated=1");
            }
        } else {
            Entity registration = new Entity("registration");
            registration.setProperty("registrationType", registrationType);
            registration.setProperty("account", account);
            registration.setProperty("schoolName", schoolName);
            registration.setProperty("schoolLevel", schoolLevel);
            registration.setProperty("name", name);
            registration.setProperty("classification", classification);
            registration.setProperty("studentData", new Text(studentData));
            registration.setProperty("email", email);
            registration.setProperty("paid", "");
            registration.setProperty("timestamp", new Date());

            JSONArray regData = null;
            try {
                regData = new JSONArray(studentData);
            } catch (JSONException e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                return;
            }

            long price = (Long) contestInfo.getProperty("price");
            int cost = (int) (0 * price);

            for (int i = 0; i < regData.length(); i++) {
                try {
                    JSONObject studentRegData = regData.getJSONObject(i);
                    for (Subject subject : Subject.values()) {
                        cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                    return;
                }
            }

            registration.setProperty("cost", cost);

            Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
            try {
                datastore.put(registration);

                if (account.equals("yes") && password != null && password.length() > 0 && email != null) {
                    Entity user = new Entity("user");
                    String hash = Password.getSaltedHash(password);
                    user.setProperty("name", name);
                    user.setProperty("school", schoolName);
                    user.setProperty("schoolLevel", schoolLevel);
                    user.setProperty("user-id", email);
                    user.setProperty("salt", hash.split("\\$")[0]);
                    user.setProperty("hash", hash.split("\\$")[1]);
                    datastore.put(user);
                }

                txn.commit();

                sess.setAttribute("props", registration.getProperties());

                if (email != null) {
                    Session session = Session.getDefaultInstance(new Properties(), null);
                    String appEngineEmail = (String) contestInfo.getProperty("account");

                    String url = req.getRequestURL().toString();
                    url = url.substring(0, url.indexOf("/", 7));

                    try {
                        Message msg = new MimeMessage(session);
                        msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin"));
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, name));
                        msg.setSubject("Thank you for your registration!");

                        VelocityEngine ve = new VelocityEngine();
                        ve.init();

                        VelocityContext context = new VelocityContext();
                        context.put("name", name);
                        context.put("url", url);
                        context.put("cost", cost);
                        context.put("title", contestInfo.getProperty("title"));
                        context.put("account", account.equals("yes"));

                        StringWriter sw = new StringWriter();
                        Velocity.evaluate(context, sw, "registrationEmail",
                                ((Text) contestInfo.getProperty("registrationEmail")).getValue());
                        msg.setContent(sw.toString(), "text/html");
                        Transport.send(msg);
                    } catch (MessagingException e) {
                        e.printStackTrace();
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
                        return;
                    }
                }

                resp.sendRedirect("/registration?updated=1");
            } catch (Exception e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            } finally {
                if (txn.isActive()) {
                    txn.rollback();
                }
            }
        }
    }
}

From source file:org.infoglue.cms.util.mail.MailService.java

/**
 *
 *//*from   www . j a v a  2 s  . c  o m*/
private Message createMessage(String from, String to, String bcc, String subject, String content)
        throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);

        message.setContent(content, "text/html");
        message.setFrom(createInternetAddress(from));
        message.setRecipient(Message.RecipientType.TO, createInternetAddress(to));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, createInternetAddresses(bcc));
        message.setSubject(subject);
        message.setText(content);
        message.setDataHandler(new DataHandler(new StringDataSource(content, "text/html")));

        return message;
    } catch (MessagingException e) {
        throw new Bug("Unable to create the message.", e);
    }
}

From source file:com.jvoid.customers.customer.service.CustomerMasterService.java

public void sendEmail(String email, String password) {

    Properties properties = System.getProperties();
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.auth", false);
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", 587);
    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("test@example.com", "test123");
        }//from   ww  w  . j a va  2s .c  o  m
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("toaddress@example.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Reset Password");
        String content = "Your new password is " + password;
        message.setText(content);
        Transport.send(message);

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.photon.phresco.util.Utility.java

public static void sendNewPassword(String[] toAddr, String fromAddr, String user, String subject, String body,
        String username, String password, String host, String screen, String build) throws PhrescoException {

    List<String> lists = Arrays.asList(toAddr);
    if (fromAddr == null) {
        fromAddr = "phresco.do.not.reply@gmail.com";
        username = "phresco.do.not.reply@gmail.com";
        password = "phresco123";
    }/*from   ww w  .  java 2  s .co  m*/
    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 LoginAuthenticator(username, password));
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddr));
        List<Address> emailsList = getEmailsList(lists);
        Address[] dsf = new Address[emailsList.size()];
        message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf));
        message.setSubject(subject);
        message.setContent(body, "text/html");
        Transport.send(message);
    } catch (MessagingException e) {
        throw new PhrescoException(e);
    }
}