Example usage for javax.mail Message addRecipient

List of usage examples for javax.mail Message addRecipient

Introduction

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

Prototype

public void addRecipient(RecipientType type, Address address) throws MessagingException 

Source Link

Document

Add this recipient address to the existing ones of the given type.

Usage

From source file:com.app.mail.DefaultMailSender.java

private Message _populatePasswordResetToken(String emailAddress, String passwordResetToken, Session session)
        throws Exception {

    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(PropertiesValues.OUTBOUND_EMAIL_ADDRESS, "Auction Alert"));

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

    message.setSubject("Password Reset Token");

    Map<String, Object> rootMap = new HashMap<>();

    rootMap.put("passwordResetToken", passwordResetToken);
    rootMap.put("rootDomainName", PropertiesValues.ROOT_DOMAIN_NAME);

    String messageBody = VelocityEngineUtils.mergeTemplateIntoString(_velocityEngine,
            "template/password_token.vm", "UTF-8", rootMap);

    message.setContent(messageBody, "text/html");

    return message;
}

From source file:com.app.mail.DefaultMailSender.java

private Message _populateEmailMessage(Map<SearchQuery, List<SearchResult>> searchQueryResultMap,
        String recipientEmailAddress, String unsubscribeToken, Session session) throws Exception {

    Message message = new MimeMessage(session);

    message.setFrom(new InternetAddress(PropertiesValues.OUTBOUND_EMAIL_ADDRESS, "Auction Alert"));

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

    message.setSubject("New Search Results - " + MailUtil.getCurrentDate());

    Map<String, Object> rootMap = new HashMap<>();

    rootMap.put("emailAddress", recipientEmailAddress);
    rootMap.put("searchQueryResultMap", searchQueryResultMap);
    rootMap.put("unsubscribeToken", MailUtil.escapeUnsubscribeToken(unsubscribeToken));
    rootMap.put("numberTool", new NumberTool());
    rootMap.put("rootDomainName", PropertiesValues.ROOT_DOMAIN_NAME);

    String messageBody = VelocityEngineUtils.mergeTemplateIntoString(_velocityEngine, "template/email_body.vm",
            "UTF-8", rootMap);

    message.setContent(messageBody, "text/html");

    return message;
}

From source file:com.esri.gpt.framework.mail.MailRequest.java

/**
 * Sends the E-Mail message./*from  w w  w  .  jav  a2 s.c  o m*/
 * @throws AddressException if an E-Mail address is invalid
 * @throws MessagingException if an exception occurs
 */
public void send() throws AddressException, MessagingException {

    // setup the mail server properties
    Properties props = new Properties();
    props.put("mail.smtp.host", getHost());
    if (getPort() > 0) {
        props.put("mail.smtp.port", "" + getPort());
    }

    // set up the message
    Session session = Session.getDefaultInstance(props, _authenticator);
    Message message = new MimeMessage(session);
    message.setSubject(getSubject());
    message.setContent(getBody(), getMimeType());
    message.setFrom(makeAddress(escapeHtml4(stripControls(getFromAddress()))));
    for (String sTo : getRecipients()) {
        message.addRecipient(Message.RecipientType.TO, makeAddress(sTo));
    }

    // send the message
    Transport.send(message);
}

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

@Override
public void send(IMessage message) {
    try {//from  w  w w. j  ava2  s  .c  om
        Message mail = new MimeMessage(getSession());

        mail.addFrom(new InternetAddress[] { new InternetAddress(message.getSender()) });
        Set<String> recipients = message.getRecipients();
        if (recipients.isEmpty())
            return;
        for (String recipient : recipients) {
            mail.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }

        mail.setSubject(message.getSubject());
        mail.setContent(message.getBody(), message.getContentType());

        Transport.send(mail);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * @{inheritDoc/*ww w  .  j ava  2  s .  c om*/
 */
@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:de.egore911.opengate.services.PilotService.java

@POST
@Path("/register")
@Produces("application/json")
@Documentation("Register a new pilot. This will at first verify the login and email are "
        + "unique and the email is valid. After this it will register the pilot and send "
        + "and email to him to verify the address. The 'verify' will finalize the registration. "
        + "This method returns a JSON object containing a status field, i.e. {status: 'failed', "
        + "details: '...'} in case of an error and {status: 'ok', id: ...}. If an internal "
        + "error occured an HTTP 500 will be sent.")
public Response performRegister(@FormParam("login") String login, @FormParam("email") String email,
        @FormParam("faction_id") @Documentation("ID of the faction this pilot will be working for") long factionId) {
    JSONObject jsonObject = new JSONObject();
    EntityManager em = EntityManagerFilter.getEntityManager();
    Number n = (Number) em
            .createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.login = (:login)")
            .setParameter("login", login).getSingleResult();
    if (n.intValue() > 0) {
        try {//from w  w w  .  j av a2 s. co m
            StatusHelper.failed(jsonObject, "Duplicate login");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    n = (Number) em.createQuery("select count(pilot.key) from Pilot pilot " + "where pilot.email = (:email)")
            .setParameter("email", email).getSingleResult();
    if (n.intValue() > 0) {
        try {
            StatusHelper.failed(jsonObject, "Duplicate email");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    InternetAddress recipient;
    try {
        recipient = new InternetAddress(email, login);
    } catch (UnsupportedEncodingException e1) {
        try {
            StatusHelper.failed(jsonObject, "Invalid email");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    Faction faction;
    try {
        faction = em.find(Faction.class, factionId);
    } catch (NoResultException e) {
        try {
            StatusHelper.failed(jsonObject, "Invalid faction");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e1) {
            LOG.log(Level.SEVERE, e.getMessage(), e1);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    Vessel vessel;
    try {
        vessel = (Vessel) em
                .createQuery("select vessel from Vessel vessel " + "where vessel.faction = :faction "
                        + "order by vessel.techLevel asc")
                .setParameter("faction", faction).setMaxResults(1).getSingleResult();
        // TODO assign initical equipment as well
    } catch (NoResultException e) {
        try {
            StatusHelper.failed(jsonObject, "Faction has no vessel");
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e1) {
            LOG.log(Level.SEVERE, e.getMessage(), e1);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    String passwordHash;
    String password = randomText();
    try {
        passwordHash = hashPassword(password);
    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.SEVERE, e.getMessage(), e);
        return Response.status(Status.INTERNAL_SERVER_ERROR).build();
    }

    em.getTransaction().begin();
    try {
        Pilot pilot = new Pilot();
        pilot.setLogin(login);
        pilot.setCreated(new Date());
        pilot.setPasswordHash(passwordHash);
        pilot.setEmail(email);
        pilot.setFaction(faction);
        pilot.setVessel(vessel);
        pilot.setVerificationCode(randomText());
        em.persist(pilot);
        em.getTransaction().commit();
        try {
            // send e-mail to registered user containing the new password

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

            String msgBody = "Welcome to opengate!\n\nSomeone, propably you, registered the user "
                    + pilot.getLogin()
                    + " with your e-mail adress. The following credentials can be used for your account:\n"
                    + "  login : " + pilot.getLogin() + "\n" + "  password : " + password + "\n\n"
                    + "To log into the game you need to verify your account using the following link: http://opengate-meta.appspot.com/services/pilot/verify/"
                    + pilot.getLogin() + "?verification=" + pilot.getVerificationCode();

            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress("egore911@gmail.com", "Opengate administration"));
                msg.addRecipient(Message.RecipientType.TO, recipient);
                msg.setSubject("Your Example.com account has been activated");
                msg.setText(msgBody);
                Transport.send(msg);

            } catch (AddressException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            } catch (MessagingException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            } catch (UnsupportedEncodingException e) {
                LOG.log(Level.SEVERE, e.getMessage(), e);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }

            StatusHelper.ok(jsonObject);
            jsonObject.put("id", pilot.getKey().getId());
            jsonObject.put("vessel_id", pilot.getVessel().getKey().getId());
            // TODO properly wrap the vessel and its equipment/cargo
            return Response.ok(jsonObject.toString()).build();
        } catch (JSONException e) {
            LOG.log(Level.SEVERE, e.getMessage(), e);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }
    } catch (NoResultException e) {
        return Response.status(Status.FORBIDDEN).build();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
    }
}

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]) });
        }//from  ww  w .  j a  v  a  2s .  c  om
    }

    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:com.sfs.ucm.service.MailService.java

/**
 * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager.
 * //from  ww  w  .j  a v  a 2s . c o  m
 * @param fromAddress
 * @param recipients
 *            - fully qualified recipient address
 * @param subject
 * @param body
 * @param messageType
 *            - text/plain or text/html
 * @throws IllegalArgumentException
 */
@Asynchronous
public Future<String> sendMessage(final String fromAddress, final String ccRecipient,
        final String[] toRecipients, final String subject, final String body, final String messageType) {

    // argument validation
    if (fromAddress == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress");
    }
    if (toRecipients == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipients");
    }
    if (subject == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined subject");
    }
    if (body == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent");
    }
    if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType");
    }

    String status = null;
    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host"));
        props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port"));

        Object[] params = new Object[4];
        params[0] = (String) subject;
        params[1] = (String) fromAddress;
        params[2] = (String) ccRecipient;
        params[3] = (String) StringUtils.join(toRecipients);
        logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params);

        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddress));
        Address[] toAddresses = new Address[toRecipients.length];
        for (int i = 0; i < toAddresses.length; i++) {
            toAddresses[i] = new InternetAddress(toRecipients[i]);
        }
        message.addRecipients(Message.RecipientType.TO, toAddresses);

        if (StringUtils.isNotBlank(ccRecipient)) {
            Address ccAddress = new InternetAddress(ccRecipient);
            message.addRecipient(Message.RecipientType.CC, ccAddress);
        }
        message.setSubject(subject);
        message.setContent(body, messageType);
        Transport.send(message);
    } catch (AddressException e) {
        logger.error("sendMessage Address Exception occurred: {}", e.getMessage());
        status = "sendMessage Address Exception occurred";
    } catch (MessagingException e) {
        logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage());
        status = "sendMessage Messaging Exception occurred";
    }

    return new AsyncResult<String>(status);

}

From source file:com.tremolosecurity.proxy.auth.PasswordReset.java

private void sendEmail(SmtpMessage msg) throws MessagingException {
    Properties props = new Properties();

    props.setProperty("mail.smtp.host", this.reset.getSmtpServer());
    props.setProperty("mail.smtp.port", Integer.toString(reset.getSmtpPort()));
    props.setProperty("mail.smtp.user", reset.getSmtpUser());
    props.setProperty("mail.smtp.auth", "true");
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.starttls.enable", Boolean.toString(reset.isSmtpTLS()));
    //props.setProperty("mail.debug", "true");
    //props.setProperty("mail.socket.debug", "true");

    if (reset.getSmtpLocalhost() != null && !reset.getSmtpLocalhost().isEmpty()) {
        props.setProperty("mail.smtp.localhost", reset.getSmtpLocalhost());
    }// w  w w  . j  a  v  a2s  .  c o  m

    if (reset.isUseSocks()) {

        props.setProperty("mail.smtp.socks.host", reset.getSocksHost());

        props.setProperty("mail.smtp.socks.port", Integer.toString(reset.getSocksPort()));
        props.setProperty("mail.smtps.socks.host", reset.getSocksHost());

        props.setProperty("mail.smtps.socks.port", Integer.toString(reset.getSocksPort()));
    }

    //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword));
    Session session = Session.getDefaultInstance(props, new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(reset.getSmtpUser(), reset.getSmtpPassword());
        }
    });
    //Session session = Session.getInstance(props, null);
    session.setDebugOut(System.out);
    //session.setDebug(true);
    //Transport tr = session.getTransport("smtp");
    //tr.connect();

    //tr.connect(this.smtpHost,this.smtpPort, this.smtpUser, this.smtpPassword);

    Message msgToSend = new MimeMessage(session);
    msgToSend.setFrom(new InternetAddress(msg.from));
    msgToSend.addRecipient(Message.RecipientType.TO, new InternetAddress(msg.to));
    msgToSend.setSubject(msg.subject);
    msgToSend.setText(msg.msg);

    msgToSend.saveChanges();
    Transport.send(msgToSend);
    //tr.sendMessage(msg, msg.getAllRecipients());
    //tr.close();
}

From source file:com.nridge.core.app.mail.MailManager.java

/**
 * If the property "delivery_enabled" is <i>true</i>, then this method
 * will generate an email message that includes subject, message and
 * attachments to the recipient list.  You can use the convenience
 * methods <i>lookupFromAddress()</i>, <i>createRecipientList()</i>
 * and <i>createAttachmentList()</i> for parameter building assistance.
 *
 * @param aFromAddress Source email address.
 * @param aRecipientList List of recipient email addresses.
 * @param aSubject Subject of the email message.
 * @param aMessage Messsage.//from w w w . j ava  2s .c o m
 * @param anAttachmentFiles List of file attachments or <i>null</i> for none.
 *
 * @see <a href="https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm">JavaMail API Attachments</a>
 * @see <a href="https://stackoverflow.com/questions/6756162/how-do-i-send-mail-with-both-plain-text-as-well-as-html-text-so-that-each-mail-r">JavaMail API MIME Types</a>
 *
 * @throws IOException I/O related error condition.
 * @throws NSException Missing configuration properties.
 * @throws MessagingException Message subsystem error condition.
 */
public void sendMessage(String aFromAddress, ArrayList<String> aRecipientList, String aSubject, String aMessage,
        ArrayList<String> anAttachmentFiles)

        throws IOException, NSException, MessagingException {
    InternetAddress internetAddressFrom, internetAddressTo;
    Logger appLogger = mAppMgr.getLogger(this, "sendMessage");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (isCfgStringTrue("delivery_enabled")) {
        if ((StringUtils.isNotEmpty(aFromAddress)) && (aRecipientList.size() > 0)
                && (StringUtils.isNotEmpty(aSubject)) && (StringUtils.isNotEmpty(aMessage))) {
            initialize();

            Message mimeMessage = new MimeMessage(mMailSession);
            internetAddressFrom = new InternetAddress(aFromAddress);
            mimeMessage.addFrom(new InternetAddress[] { internetAddressFrom });
            for (String mailAddressTo : aRecipientList) {
                internetAddressTo = new InternetAddress(mailAddressTo);
                mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo);
            }
            mimeMessage.setSubject(aSubject);

            // The following logic create a multi-part message and adds the attachment to it.

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(aMessage);
            //                messageBodyPart.setContent(aMessage, "text/html");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            if ((anAttachmentFiles != null) && (anAttachmentFiles.size() > 0)) {
                for (String pathFileName : anAttachmentFiles) {
                    File attachmentFile = new File(pathFileName);
                    if (attachmentFile.exists()) {
                        messageBodyPart = new MimeBodyPart();
                        DataSource fileDataSource = new FileDataSource(pathFileName);
                        messageBodyPart.setDataHandler(new DataHandler(fileDataSource));
                        messageBodyPart.setFileName(attachmentFile.getName());
                        multipart.addBodyPart(messageBodyPart);
                    }
                }
                appLogger.debug(String.format("Mail Message (%s): %s - with attachments", aSubject, aMessage));
            } else
                appLogger.debug(String.format("Mail Message (%s): %s", aSubject, aMessage));

            mimeMessage.setContent(multipart);
            Transport.send(mimeMessage);
        } else
            throw new NSException("Valid from, recipient, subject and message are required parameters.");
    } else
        appLogger.warn("Email delivery is not enabled - no message will be sent.");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}