Example usage for javax.mail Transport send

List of usage examples for javax.mail Transport send

Introduction

In this page you can find the example usage for javax.mail Transport send.

Prototype

public static void send(Message msg) throws MessagingException 

Source Link

Document

Send a message.

Usage

From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java

public boolean dispatch(BIObject document, byte[] executionOutput) {
    Map parametersMap;//  w  w  w . j a  va2  s.c  o  m
    String contentType;
    String fileExtension;
    IDataStore emailDispatchDataStore;
    String nameSuffix;
    String descriptionSuffix;
    String containedFileName;
    String zipFileName;
    boolean reportNameInSubject;

    logger.debug("IN");
    try {
        parametersMap = dispatchContext.getParametersMap();
        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        emailDispatchDataStore = dispatchContext.getEmailDispatchDataStore();
        nameSuffix = dispatchContext.getNameSuffix();
        descriptionSuffix = dispatchContext.getDescriptionSuffix();
        containedFileName = dispatchContext.getContainedFileName() != null
                && !dispatchContext.getContainedFileName().equals("") ? dispatchContext.getContainedFileName()
                        : document.getName();
        zipFileName = dispatchContext.getZipMailName() != null && !dispatchContext.getZipMailName().equals("")
                ? dispatchContext.getZipMailName()
                : document.getName();
        reportNameInSubject = dispatchContext.isReportNameInSubject();

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        int smptPort = 25;

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";
        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        if ((user == null) || user.trim().equals("")) {
            logger.debug("Smtp user not configured");
            user = null;
        }
        //   throw new Exception("Smtp user not configured");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
        if ((pass == null) || pass.trim().equals("")) {
            logger.debug("Smtp password not configured");
        }
        //   throw new Exception("Smtp password not configured");

        String mailSubj = dispatchContext.getMailSubj();
        mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false);

        String mailTxt = dispatchContext.getMailTxt();

        String[] recipients = findRecipients(dispatchContext, document, emailDispatchDataStore);
        if (recipients == null || recipients.length == 0) {
            logger.error("No recipients found for email sending!!!");
            return false;
        }

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        // open session
        Session session = null;

        // create autheticator object
        Authenticator auth = null;
        if (user != null) {
            auth = new SMTPAuthenticator(user, pass);
            props.put("mail.smtp.auth", "true");
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }

            //session = Session.getDefaultInstance(props, auth);
            session = Session.getInstance(props, auth);
            //session.setDebug(true);
            //session.setDebugOut(null);
            logger.info("Session.getInstance(props, auth)");

        } else {
            //session = Session.getDefaultInstance(props);
            session = Session.getInstance(props);
            logger.info("Session.getInstance(props)");
        }

        // 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

        String subject = mailSubj;

        if (reportNameInSubject) {
            subject += " " + document.getName() + nameSuffix;
        }

        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(mailTxt + "\n" + descriptionSuffix);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message

        SchedulerDataSource sds = null;
        //if zip requested
        if (dispatchContext.isZipMailDocument()) {
            mbp2 = zipAttachment(executionOutput, containedFileName, zipFileName, nameSuffix, fileExtension);
        }
        //else 
        else {
            sds = new SchedulerDataSource(executionOutput, contentType,
                    containedFileName + nameSuffix + fileExtension);
            mbp2.setDataHandler(new DataHandler(sds));
            mbp2.setFileName(sds.getName());
        }

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }
    return true;
}

From source file:org.pentaho.platform.util.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {//from ww w .  jav a  2  s.  co  m
        // Get a Session object
        Session session;

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

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        final MimeMessage msg;

        if (EMBEDDED_HTML.equals(attachmentMimeType)) {

            //Message is ready
            msg = new MimeMessage(session, attachment);

            if (body != null) {
                //We need to add message to the top of the email body
                final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent();
                final MimeMultipart newMultipart = new MimeMultipart("related");

                for (int i = 0; i < oldMultipart.getCount(); i++) {
                    BodyPart bodyPart = oldMultipart.getBodyPart(i);

                    final Object content = bodyPart.getContent();
                    //Main HTML body
                    if (content instanceof String) {
                        final String newContent = body + "<br/><br/>" + content;
                        final MimeBodyPart part = new MimeBodyPart();
                        part.setText(newContent, "UTF-8", "html");
                        newMultipart.addBodyPart(part);
                    } else {
                        //CID attachments
                        newMultipart.addBodyPart(bodyPart);
                    }
                }

                msg.setContent(newMultipart);
            }
        } else {

            // construct the message
            msg = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            if (attachment == null) {
                logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
                return false;
            }

            ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

            if (body != null) {
                MimeBodyPart bodyMessagePart = new MimeBodyPart();
                bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(bodyMessagePart);
            }

            // attach the file to the message
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
            multipart.addBodyPart(attachmentBodyPart);

            // add the Multipart to the message
            msg.setContent(multipart);
        }

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:com.ikon.util.MailUtils.java

/**
 * Forward a mail in the repository./*from w ww  .  j  av a2s.  c o  m*/
 * 
 * @param token Authentication token.
 * @param fromAddress Origin address.
 * @param toAddress Destination addresses.
 * @param mailId Path of the mail to be forwarded or its UUID.
 * @throws MessagingException If there is any error.
 */
public static void forwardMail(String token, String fromAddress, Collection<String> toAddress, String message,
        String mailId) throws MessagingException, PathNotFoundException, AccessDeniedException,
        RepositoryException, IOException, DatabaseException {
    log.debug("forwardMail({}, {}, {}, {}, {})", new Object[] { token, fromAddress, toAddress, mailId });
    Mail mail = OKMMail.getInstance().getProperties(token, mailId);
    mail.setSubject("Fwd: " + mail.getSubject());

    if (Mail.MIME_TEXT.equals(mail.getMimeType())) {
        mail.setContent(message + "\n\n---------- Forwarded message ----------\n\n" + mail.getContent());
    } else if (Mail.MIME_HTML.equals(mail.getMimeType())) {
        mail.setContent(
                message + "<br/><br/>---------- Forwarded message ----------<br/><br/>" + mail.getContent());
    } else {
        log.warn("Email does not specify content MIME type");
    }

    if (fromAddress != null) {
        mail.setFrom(fromAddress);
    }

    if (toAddress != null && !toAddress.isEmpty()) {
        String[] to = (String[]) toAddress.toArray(new String[toAddress.size()]);
        mail.setTo(to);
    }

    MimeMessage m = create(token, mail);
    Transport.send(m);
    log.debug("forwardMail: void");
}

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  www.j a v a2s . c  o  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:net.sourceforge.fenixedu.presentationTier.Action.ExceptionHandlingAction.java

private void sendEmail(String from, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host",
            Objects.firstNonNull(FenixConfigurationManager.getConfiguration().getMailSmtpHost(), "localhost"));
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    try {/*from  www.  ja va 2s. co m*/
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress()));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
    } catch (Exception e) {
        logger.error("Could not send support email! Original message was: " + body, e);
    }
}

From source file:org.socraticgrid.hl7.ucs.nifi.processor.SendEmail.java

private String sendEmail(String emailSubject, String fromEmail, String toEmail, String emailBody,
        String mimeType, String charset, String smtpServerUrl, String smtpServerPort, String username,
        String password, ServiceStatusController serviceStatusControllerService) throws Exception {

    String statusMessage = "Email sent successfully to " + toEmail;

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", smtpServerUrl);
    props.put("mail.smtp.port", smtpServerPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/* w w  w  . j  a v a2s .  c o  m*/
    });
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject(emailSubject);
        message.setContent(emailBody, mimeType + "; charset=" + charset);
        Transport.send(message);
        getLogger().info("Email sent successfully!");
        serviceStatusControllerService.updateServiceStatus("EMAIL", Status.AVAILABLE);
    } catch (MessagingException e) {
        serviceStatusControllerService.updateServiceStatus("EMAIL", Status.UNAVAILABLE);
        getLogger().error("Unable to send Email! Reason : " + e.getMessage(), e);
        statusMessage = "Unable to send Email! Reason : " + e.getMessage();
        throw new RuntimeException(e);
    }
    return statusMessage;
}

From source file:edu.umich.ctools.sectionsUtilityTool.Friend.java

public static void notifyCurrentUser(String instructorName, String instructorEmail, String inviteEmail) {

    M_log.debug("Friend notifyCurrentUser() called");
    String to = instructorEmail;/*from   ww  w .  j  ava 2 s  . c om*/
    String from = contactEmail;
    String host = mailHost;

    M_log.info("Setting up mailProps");

    Properties properties = System.getProperties();
    properties.put(MAIL_SMTP_AUTH, "false");
    properties.put(MAIL_SMTP_STARTTLS, "true"); //Put to false, if no https is needed
    properties.put(MAIL_SMTP_HOST, host);
    properties.put(MAIL_DEBUG, "true");

    M_log.debug("Initiating Session for sendMail");
    Session session = Session.getInstance(properties);

    try {

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("<instructor>", instructorName);
        map.put("<friend>", inviteEmail);

        emailMessage = Friend.readFile(requesterEmailFile, StandardCharsets.UTF_8);
        emailMessage = replacePlaceHolders(emailMessage, map);

        M_log.debug("Setting up message for sendMail");
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subjectLine);

        message.setText(emailMessage);

        M_log.info("Sending message");
        Transport.send(message);

        M_log.info("Message sent to " + instructorName);

    } catch (Exception e) {
        M_log.error("notifyCurrentUser exception: " + e.getMessage());
    }
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist.
 *
 * Json sent should have following keys :
 *
 * - to      : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"]
 * - cc      : json array of email to 'CC' email ex: ["him@rm.fr"]
 * - bcc     : json array of email to add recipient as blind CC ["secret@rm.fr"]
 * - subject : subject of email//from  w w w.  j  a v  a  2s  . c  o  m
 * - body    : Body of email
 *
 * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory.
 *
 * complete json example :
 *
 * {
 *   "to": ["you@rm.fr", "another-guy@rm.fr"],
 *   "cc": ["him@rm.fr"],
 *   "bcc": ["secret@rm.fr"],
 *   "subject": "test email",
 *   "body": "Hi, this a test EMail, please do not reply."
 * }
 *
 */
@RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json")
@ResponseBody
public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request)
        throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException {

    JSONObject payload = new JSONObject(rawRequest);
    InternetAddress[] to = this.populateRecipient("to", payload);
    InternetAddress[] cc = this.populateRecipient("cc", payload);
    InternetAddress[] bcc = this.populateRecipient("bcc", payload);

    this.checkSubject(payload);
    this.checkBody(payload);
    this.checkRecipient(to, cc, bcc);

    LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to="
            + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc="
            + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles"));

    LOG.debug("EMail request : " + payload.toString());

    // Instanciate MimeMessage
    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    MimeMessage message = new MimeMessage(session);

    // Generate From header
    InternetAddress from = new InternetAddress();
    from.setAddress(this.georConfig.getProperty("emailProxyFromAddress"));
    from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setFrom(from);

    // Generate Reply-to header
    InternetAddress replyTo = new InternetAddress();
    replyTo.setAddress(request.getHeader("sec-email"));
    replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname"));
    message.setReplyTo(new Address[] { replyTo });

    // Generate to, cc and bcc headers
    if (to.length > 0)
        message.setRecipients(Message.RecipientType.TO, to);
    if (cc.length > 0)
        message.setRecipients(Message.RecipientType.CC, cc);
    if (bcc.length > 0)
        message.setRecipients(Message.RecipientType.BCC, bcc);

    // Add subject and body
    message.setSubject(payload.getString("subject"), "UTF-8");
    message.setText(payload.getString("body"), "UTF-8", "plain");
    message.setSentDate(new Date());

    // finally send message
    Transport.send(message);

    JSONObject res = new JSONObject();
    res.put("success", true);
    return res.toString();
}

From source file:org.apache.jmeter.reporters.MailerModel.java

/**
 * Sends a mail with the given parameters using SMTP.
 *
 * @param from/*  w w w. ja v  a2s.  c  om*/
 *            the sender of the mail as shown in the mail-client.
 * @param vEmails
 *            all receivers of the mail. The receivers are seperated by
 *            commas.
 * @param subject
 *            the subject of the mail.
 * @param attText
 *            the message-body.
 * @param smtpHost
 *            the smtp-server used to send the mail.
 * @param smtpPort the smtp-server port used to send the mail.
 * @param user the login used to authenticate
 * @param password the password used to authenticate
 * @param mailAuthType {@link MailAuthType} Security policy
 * @param debug Flag whether debug messages for the mail session should be generated
 * @throws AddressException If mail address is wrong
 * @throws MessagingException If building MimeMessage fails
 */
public void sendMail(String from, List<String> vEmails, String subject, String attText, String smtpHost,
        String smtpPort, final String user, final String password, MailAuthType mailAuthType, boolean debug)
        throws AddressException, MessagingException {

    InternetAddress[] address = new InternetAddress[vEmails.size()];

    for (int k = 0; k < vEmails.size(); k++) {
        address[k] = new InternetAddress(vEmails.get(k));
    }

    // create some properties and get the default Session
    Properties props = new Properties();

    props.put(MAIL_SMTP_HOST, smtpHost);
    props.put(MAIL_SMTP_PORT, smtpPort); // property values are strings
    Authenticator authenticator = null;
    if (mailAuthType != MailAuthType.NONE) {
        props.put(MAIL_SMTP_AUTH, "true");
        switch (mailAuthType) {
        case SSL:
            props.put(MAIL_SMTP_SOCKETFACTORY_CLASS, "javax.net.ssl.SSLSocketFactory");
            break;
        case TLS:
            props.put(MAIL_SMTP_STARTTLS, "true");
            break;

        default:
            break;
        }
    }

    if (!StringUtils.isEmpty(user)) {
        authenticator = new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        };
    }
    Session session = Session.getInstance(props, authenticator);
    session.setDebug(debug);

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

    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);
    msg.setText(attText);
    Transport.send(msg);
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraFailed(String adresaSephora, String from, String to1, String to2,
        String grupSephora, String subject, String filename) throws FileNotFoundException, IOException {

    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }/*from   w ww  .j a  v a2  s. co m*/
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        //send message  
        Transport.send(message);

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

}