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:org.openbizview.util.Bvt002.java

/**
* Enva notificacin a usuario al cambiar la contrasea
**///from www .  java 2s. c o m
private void ChangePassNotification2(String mail, String clave) {
    try {
        Context initContext = new InitialContext();
        Session session = (Session) initContext.lookup(JNDIMAIL);
        // Crear el mensaje a enviar
        MimeMessage mm = new MimeMessage(session);
        // Establecer las direcciones a las que ser enviado
        // el mensaje (test2@gmail.com y test3@gmail.com en copia
        // oculta)
        // mm.setFrom(new
        // InternetAddress("opennomina@dvconsultores.com"));
        mm.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));

        // Establecer el contenido del mensaje
        mm.setSubject(getMessage("mailUserUserChgPass"));
        mm.setText(getMessage("mailNewUserMsj2"));

        // use this is if you want to send html based message
        mm.setContent(getMessage("mailNewUserMsj6") + " " + coduser.toUpperCase() + " / " + clave
                + "<br/><br/> " + getMessage("mailNewUserMsj2"), "text/html; charset=utf-8");

        // Enviar el correo electrnico
        Transport.send(mm);
        //System.out.println("Correo enviado exitosamente");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:cz.incad.vdkcommon.solr.Indexer.java

private void sendDemandMail(SolrDocument resultDoc, String id) {
    try {// ww  w. j ava2  s.co  m
        String title = (String) resultDoc.getFieldValues("title").toArray()[0];
        String pop = (String) resultDoc.getFieldValue("poptavka_ext");
        JSONObject j = new JSONObject(pop);

        String from = opts.getString("admin.email");
        Knihovna kn = new Knihovna(j.getString("knihovna"));
        String to = kn.getEmail();
        String zaznam = j.optString("zaznam");
        String code = j.optString("code");
        String exemplar = j.optString("exemplar");
        try {
            Properties properties = System.getProperties();
            Session session = Session.getDefaultInstance(properties);

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

            message.setSubject(opts.getString("admin.email.demand.subject"));

            String link = opts.getString("app.url") + "/original?id=" + id;
            String body = opts.getString("admin.email.demand.body").replace("${demand.title}", title)
                    .replace("${demand.url}", link);
            message.setText(body);

            Transport.send(message);
            LOGGER.fine("Sent message successfully....");
        } catch (MessagingException ex) {
            LOGGER.log(Level.SEVERE, "Error sending email to: {0}, from {1} ", new Object[] { to, from });
            LOGGER.log(Level.SEVERE, null, ex);
        }
    } catch (NamingException | SQLException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }
}

From source file:trendplot.TrendPlot.java

private void emailResults() throws IOException, WebUtilException {
    emailStart = System.currentTimeMillis();

    ViewerConfig vc = new ViewerConfig();
    if (!config.isEmpty()) {
        vc.setConfigFileName(config);/*from w  w  w .  j  a  v a  2s  .c  om*/
    }
    vc.readConfig();
    String host = vc.get("webserver");
    if (host == null || host.isEmpty()) {
        host = "ldvw.ligo.caltech.edu";
    }
    String servlet = vc.get("servlet");
    if (servlet == null || servlet.isEmpty()) {
        servlet = "ldvw/view";
    }
    PageItemList msg = new PageItemList();

    if (!imgIds.isEmpty()) {
        msg.add(new PageItemHeader("The following results are available:", 3));
        PageTable tbl = new PageTable();
        for (int img = 0; img < imgIds.size(); img++) {
            PageTableRow row = new PageTableRow();
            row.add(descriptions.get(img));
            Integer imgId = imgIds.get(img);
            String url = "https://" + host + "/" + servlet + "?act=getimg&amp;imgId=" + imgId.toString();
            PageItemTextLink link = new PageItemTextLink(url, "link");
            row.add(link);
            tbl.addRow(row);
        }
        msg.add(tbl);
        msg.addBlankLines(2);

        String groupIntro = String.format("These images have also been added to the %1$s group.<br>", group);
        msg.add(new PageItemString(groupIntro, false));
        String groupUrl = String.format(
                "https://%1$s/%2$s?act=imagehistory&amp;group=%3$s" + "&amp;usrSel=%4$s", host, servlet, group,
                user);
        PageItemTextLink groupLink = new PageItemTextLink(groupUrl, "Click for image group page.");
        msg.add(groupLink);
        msg.addBlankLines(2);
    } else if (!checkOnly) {
        msg.add("Sorry but no images were produced.");
        msg.addBlankLines(2);
    }
    if (verbose || imgIds.isEmpty()) {
        msg.add(new PageItemString("<br>Stdout:<br><br>", false));
        String outText = outStringWriter.toString().replace("\n", "<br>\n");
        msg.add(new PageItemString(outText, false));

        msg.add(new PageItemString("<br>Stderr:<br><br>", false));
        outText = errStringWriter.toString().replace("\n", "<br>\n");
        msg.add(new PageItemString(outText, false));
    }
    msg.add(new PageItemString("<br><br>Sincerly,<br>The LigoDV-web group", false));

    Float condor = (startTime - qtime) / 1000.f;
    String condorTime = qtime == 0 ? "?" : String.format("%1$.2f", condor);
    Float overhead = (transferStart - startTime) / 1000.f;
    Float xfer = (plotStart - transferStart) / 1000.f;
    Float plot = (emailStart - plotStart) / 1000.f;
    String timing = String.format(
            "Timing: queue: %1$s, overhead: %2$.2f, data collection: %3$.2f, " + "plot: %4$.2f seconds",
            condorTime, overhead, xfer, plot);
    outPrintWriter.println(timing);
    msg.addBlankLines(2);
    msg.add(new PageItemString(timing, false));
    msg.addBlankLines(1);

    String msgText = msg.getHtml();

    Properties fMailServerConfig;
    fMailServerConfig = new Properties();
    fMailServerConfig.setProperty("mail.host", "ldas-cit.ligo.caltech.edu");
    fMailServerConfig.setProperty("mail.smtp.host", "ldas-cit.ligo.caltech.edu");

    Session session = Session.getDefaultInstance(fMailServerConfig, null);
    MimeMessage message = new MimeMessage(session);
    try {
        //the "from" address may be set in code, or set in the
        //config file under "mail.from" ; here, the latter style is used
        message.setFrom(new InternetAddress("areeda@ligo.caltech.edu"));

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

        message.setSubject("Trend plot results are available.");
        message.setText(msgText, "utf-8", "html");
        Transport.send(message);
        outPrintWriter.format("Email sent to %1$s\n", email);
        errPrintWriter.println("Email message:");
        errPrintWriter.println(msgText);
    } catch (MessagingException ex) {
        throw new WebUtilException("Cannot send email. " + ex);
    }
}

From source file:trendplot.TrendPlot.java

private void testEmail() {
    Properties fMailServerConfig;
    fMailServerConfig = new Properties();
    fMailServerConfig.setProperty("mail.host", "ldas-cit.ligo.caltech.edu");
    fMailServerConfig.setProperty("mail.smtp.host", "ldas-cit.ligo.caltech.edu");

    Session session = Session.getDefaultInstance(fMailServerConfig, null);
    MimeMessage message = new MimeMessage(session);
    try {//www. j av  a2s  .c  o m
        //the "from" address may be set in code, or set in the
        //config file under "mail.from" ; here, the latter style is used
        message.setFrom(new InternetAddress("areeda@ligo.caltech.edu"));
        String email = "joe@areeda.com";

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
        String msg = "<h3>this is a test</h3>";
        message.setSubject("Test email");
        message.setText(msg, "utf-8", "html");
        Transport.send(message);
        System.out.format("Email sent to %1$s\n", email);
    } catch (MessagingException ex) {
        System.err.format("Exception: %1$s: %2$s", ex.getClass().getSimpleName(), ex.getLocalizedMessage());
    }

}

From source file:au.aurin.org.controller.RestController.java

public Boolean sendEmail(final String randomUUIDString, final String password, final String email,
        final List<String> lstApps, final String fullName) throws IOException {
    final String clink = classmail.getUrl() + "authchangepassword/" + randomUUIDString;

    logger.info("Starting sending Email to:" + email);
    String msg = "";

    if (!fullName.equals("")) {
        msg = msg + "Dear " + fullName + "<br>";
    }//from  ww w .  jav  a2s  . com
    Boolean lswWhatIf = false;
    if (lstApps != null) {
        //msg = msg + "You have been given access to the following applications: <br>";
        msg = msg + "<br>You have been given access to the following applications: <br>";
        for (final String st : lstApps) {
            if (st.toLowerCase().contains("whatif") || st.toLowerCase().contains("what if")) {

                lswWhatIf = true;
            }
            msg = "<br>" + msg + st + "<br>";
        }

    }

    msg = msg + "<br>Your current password is : " + password
            + " <br> To customise the password please change it using link below: <br> <a href='" + clink
            + "'> change password </a><br><br>After changing your password you can log in to the applications using your email and password. ";

    final String subject = "AURIN Workbench Access";

    final String from = classmail.getFrom();
    final String to = email;

    if (lswWhatIf == true) {
        msg = msg
                + "<br><br>If you require further support to establish a project within Online WhatIf please email your request to support@aurin.org.au";
        msg = msg + "<br>For other related requests please contact one of the members of the project team.";
        msg = msg + "<br><br>Kind Regards,";
        msg = msg + "<br>The Online WhatIf team<br>";
        msg = msg
                + "<br><strong>Prof Christopher Pettit</strong>&nbsp;&nbsp;&nbsp;&nbsp;Online WhatIf Project Director, City Futures (c.pettit@unsw.edu.au)";
        msg = msg
                + "<br><strong>Claudia Pelizaro</strong>&nbsp;&nbsp;&nbsp;&nbsp;Online WhatIf Project Manager, AURIN (claudia.pelizaro@unimelb.edu.au)";
        msg = msg
                + "<br><strong>Andrew Dingjan</strong>&nbsp;&nbsp;&nbsp;&nbsp;Director, AURIN (andrew.dingjan@unimelb.edu.au)";
        msg = msg
                + "<br><strong>Serryn Eagleson</strong>&nbsp;&nbsp;&nbsp;&nbsp;Manager Data and Business Analytics (serrynle@unimelb.edu.au)";

    } else {
        msg = msg + "<br><br>Kind Regards,";
        msg = msg + "<br>The AURIN Workbench team";
    }

    try {
        final Message message = new MimeMessage(getSession());

        message.addRecipient(RecipientType.TO, new InternetAddress(to));
        message.addFrom(new InternetAddress[] { new InternetAddress(from) });

        message.setSubject(subject);
        message.setContent(msg, "text/html");

        //////////////////////////////////
        final MimeMultipart multipart = new MimeMultipart("related");
        final BodyPart messageBodyPart = new MimeBodyPart();
        //final String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";

        msg = msg + "<br><br><img src=\"cid:AbcXyz123\" />";
        //msg = msg + "<img src=\"cid:image\">";
        messageBodyPart.setContent(msg, "text/html");
        // add it
        multipart.addBodyPart(messageBodyPart);

        /////// second part (the image)
        //      messageBodyPart = new MimeBodyPart();
        final URL peopleresource = getClass().getResource("/logo.jpg");
        logger.info(peopleresource.getPath());
        //            final DataSource fds = new FileDataSource(
        //                peopleresource.getPath());
        //
        //      messageBodyPart.setDataHandler(new DataHandler(fds));
        //      messageBodyPart.setHeader("Content-ID", "<image>");
        //      // add image to the multipart
        //      //multipart.addBodyPart(messageBodyPart);

        ///////////
        final MimeBodyPart imagePart = new MimeBodyPart();
        imagePart.attachFile(peopleresource.getPath());
        //      final String cid = "1";
        //      imagePart.setContentID("<" + cid + ">");
        imagePart.setHeader("Content-ID", "AbcXyz123");
        imagePart.setDisposition(MimeBodyPart.INLINE);
        multipart.addBodyPart(imagePart);

        // put everything together
        message.setContent(multipart);
        ////////////////////////////////

        Transport.send(message);
        logger.info("Email sent to:" + email);
    } catch (final Exception mex) {
        logger.info(mex.toString());
        return false;
    }

    return true;
}

From source file:userinterface.DoctorWorkArea.DiagnosePatientJPanel.java

private void addtoCartButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addtoCartButton6ActionPerformed
    // TODO add your handling code here:

    int selectedRow = productTable.getSelectedRow();
    if (selectedRow < 0) {
        JOptionPane.showMessageDialog(null, "Please select a Product from the Table");
        return;/*from  www . j  a va  2 s.  c om*/
    }

    Product product = (Product) productTable.getValueAt(selectedRow, 0);
    int quantity = (Integer) quantitySpinner.getValue();
    if (quantity == 0) {
        JOptionPane.showMessageDialog(null, "Please enter a number for Medicine Quantity!");
        return;
    }

    if (product != null) {
        updateQuantity(product, quantity, SUBTRACT);
    }
    String medName = product.getProdName();

    Employee patient = (Employee) patientCombo1.getSelectedItem();
    patient.getMedicalRecord().setMedicinePrescribed(medName);
    String email = patient.getEmail();

    if (email.trim().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Patient profile is not updated for email!");
        return;
    }

    if (isValidEmailAddress(email)) {
        String uuid = UUID.randomUUID().toString();
        //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample");

        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("neelzsaxena@gmail.com", "painforever24");
            }

        }

        );
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("neelzsaxena@gmail.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
            message.setSubject("Prescribed Medicines");
            message.setText("The medicine Prescribed is :" + medName + '\n' + "The Quantity authorized is:"
                    + quantity + '\n' + "The unique barcode is:" + uuid);
            Transport.send(message);
            populateTable();
            JOptionPane.showMessageDialog(null, "message sent");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "message failed");
        }

    } else {
        JOptionPane.showMessageDialog(null, "Invalid Email Id");
        return;
    }

    //        String uuid = UUID.randomUUID().toString();
    //        //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample");
    //        
    //        Properties props = new Properties();
    //        props.put("mail.smtp.host", "smtp.gmail.com");
    //        props.put("mail.smtp.socketFactory.port", "465");
    //        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    //        props.put("mail.smtp.auth", "true");
    //        props.put("mail.smtp.port", "465");
    //
    //            Session  session = Session.getDefaultInstance(props,
    //                    new javax.mail.Authenticator(){
    //                        protected PasswordAuthentication getPasswordAuthentication(){
    //      return new PasswordAuthentication("neelzsaxena@gmail.com", "painforever24");
    //                    }
    //   
    //            }
    //
    //   );
    //        try{
    //            Message message = new MimeMessage(session);
    //            message.setFrom(new InternetAddress("neelzsaxena@gmail.com"));
    //            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
    //            message.setSubject("Prescribed Medicines");
    //            message.setText("The medicine Prescribed is :" +medName + '\n'+
    //                            "The Quantity authorized is:"+quantity + '\n'+
    //                            "The unique barcode is:"+uuid);
    //                Transport.send(message);
    //                    populateTable();
    //                    JOptionPane.showMessageDialog(null,"message sent");
    //            }catch(Exception e){
    //                JOptionPane.showMessageDialog(null,"message failed");
    //            }

}

From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java

private void sendMail(DispatchContext sInfo, BIObject biobj, Map parMap, byte[] response, String retCT,
        String fileExt, IDataStore dataStore, String toBeAppendedToName, String toBeAppendedToDescription) {
    logger.debug("IN");
    try {/*from   www.  ja va  2 s.  c  om*/

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        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 = sInfo.getMailSubj();
        mailSubj = StringUtilities.substituteParametersInString(mailSubj, parMap, null, false);

        String mailTxt = sInfo.getMailTxt();

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

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", 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");
            session = Session.getDefaultInstance(props, auth);
            logger.error("Session.getDefaultInstance(props, auth)");
        } else {
            session = Session.getDefaultInstance(props);
            logger.error("Session.getDefaultInstance(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 + " " + biobj.getName() + toBeAppendedToName;
        msg.setSubject(subject);
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(mailTxt + "\n" + toBeAppendedToDescription);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message

        SchedulerDataSource sds = new SchedulerDataSource(response, retCT,
                biobj.getName() + toBeAppendedToName + fileExt);
        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
        Transport.send(msg);
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
    } finally {
        logger.debug("OUT");
    }
}

From source file:UserInfo_Frame.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port ", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("anhduc.nguyen77000@gmail.com", "Matmachung020587");
        }/*from  w  ww . ja v  a  2s  .c  o  m*/
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("anhduc.nguyen77000@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("oracle.submit@gmail.com"));
        message.setSubject("hi this is me");
        message.setText("hi how are you, i am fine");
        Transport.send(message);
        JOptionPane.showMessageDialog(null, "message sent");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

From source file:smilehouse.opensyncro.pipes.Pipe.java

private void addLogEntry(LogEntry logEntry, int statusCode) {
    if (this.log == null)
        this.log = new HashSet();

    logEntry.setStatusCode(statusCode);//from w  w w.j  a v a  2 s. com
    logEntry.setTime(new Date());

    // The LogEntry is not explicitly added to the Pipe's log Set, since it causes
    // Hibernate to query all LogEntries from the database and thus consume
    // ever-increasing amount of server resources.

    //this.log.add(logEntry);
    String status = getStatusString(statusCode);

    Persister persister = new Persister(database);

    try {
        persister.update(logEntry);

        List messages;

        boolean mailAddressNotSet = ((getMailHost() == null || getRecipientAddress() == null)
                || (getMailHost().length() == 0 || getRecipientAddress().length() == 0));

        // Notification via email only if host and email address are present
        if (!mailAddressNotSet && !(getTransferLogNotificationLevel() == MessageLogger.MAIL_NONE)) {

            String date = dateFormat.format(new Date());
            String subject = this.getName() + " " + status + " " + date + " (" + database + ")";
            String message = "";

            // Get number of log messages at or below transferLogNotificationLevel.  

            int entries = persister.getLogMessageEntries(logEntry.getId(), getTransferLogNotificationLevel())
                    .size();

            //Generate mail message
            if (entries > 0) {

                messages = persister.getLogMessageEntries(logEntry.getId(), getLoggingVerbosityLevel());
                for (Iterator m = messages.iterator(); m.hasNext();) {
                    LogMessageEntry messageEntry = (LogMessageEntry) m.next();
                    message += (messageEntry.getMessage()) + "\n";
                }
            } else {
                message += MAIL_MESSAGE_NO_ENTRIES;
            }

            // Send notification email except when the message is
            // MAIL_MESSAGE_NO_ENTRIES or the pipe has aborted and 
            // isAbortMailEnabled()==true 
            if (!message.equals(MAIL_MESSAGE_NO_ENTRIES)
                    || (statusCode == LogEntry.STATUS_ABORTED && isAbortMailEnabled())) {
                try {

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

                    Session mailConnection = Session.getInstance(props, null);
                    Message msg = new MimeMessage(mailConnection);
                    Address sender = new InternetAddress(MAIL_SENDER + "@" + getMailHost(), MAIL_SENDER);
                    Address[] receivers = receiverAddresses(getRecipientAddress());

                    // Set mail content and subject
                    msg.setContent(message, "text/plain");
                    msg.setFrom(sender);
                    msg.setRecipients(Message.RecipientType.TO, receivers);
                    msg.setSubject(subject);

                    // Send the mail
                    Transport.send(msg);

                } catch (MessagingException e) {
                    String error = "An error occurred when sending mail report from " + MAIL_SENDER + "@"
                            + getMailHost() + " to " + getRecipientAddress() + ":\n" + e.getMessage();
                    Environment.getInstance().log(error);
                    logEntry.logMessage(error, this, MessageLogger.ERROR);
                    persister.update(logEntry);
                } catch (RuntimeException ex) {
                    Environment.getInstance().log("A RuntimeException has occurred: " + ex.getMessage()
                            + ex.getStackTrace().toString());
                }
            }
        }
        // Remove unnecessary (debug level) messages from the LogEntry if Transfer log
        // verbosity level is set to DYNAMIC and the current LogEntry's status is either
        // OK or ABORTED
        if (getLoggingVerbosityLevel() == MessageLogger.LOG_DYNAMIC
                && (statusCode == LogEntry.STATUS_OK || statusCode == LogEntry.STATUS_ABORTED)) {
            messages = persister.getLogMessageEntries(logEntry.getId(), MessageLogger.DEBUG);
            if (messages.size() > 0) {
                for (Iterator m = messages.iterator(); m.hasNext();) {
                    LogMessageEntry messageEntry = (LogMessageEntry) m.next();
                    if (messageEntry.getMessageType() == MessageLogger.DEBUG) {
                        persister.delete(messageEntry);

                    }
                }
            }
        }
    } catch (Exception e) {
        Environment.getInstance().log(e.getMessage());
    } finally {
        persister.close();
    }
}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

public void sendEmail(javax.mail.Session session, boolean rich, InternetAddress from, InternetAddress[] to,
        InternetAddress[] cc, InternetAddress[] bcc, String subject, String body, MimeBodyPart[] parts)
        throws MessagingException {

    //Session session=getGlobalMailSession(pid.getDomainId());
    MimeMessage msg = new MimeMessage(session);
    try {/*from  w w w .  j  a  v  a 2s. co  m*/
        subject = MimeUtility.encodeText(subject);
    } catch (Exception exc) {
    }
    msg.setSubject(subject);
    msg.addFrom(new InternetAddress[] { from });

    if (to != null)
        for (InternetAddress addr : to) {
            msg.addRecipient(Message.RecipientType.TO, addr);
        }

    if (cc != null)
        for (InternetAddress addr : cc) {
            msg.addRecipient(Message.RecipientType.CC, addr);
        }

    if (bcc != null)
        for (InternetAddress addr : bcc) {
            msg.addRecipient(Message.RecipientType.BCC, addr);
        }

    body = StringUtils.defaultString(body);
    MimeMultipart mp = new MimeMultipart("mixed");
    if (rich) {
        MimeMultipart alternative = new MimeMultipart("alternative");
        MimeBodyPart mbp2 = new MimeBodyPart();
        mbp2.setContent(body, MailUtils.buildPartContentType("text/html", "UTF-8"));
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(MailUtils.htmlToText(MailUtils.htmlunescapesource(body)),
                MailUtils.buildPartContentType("text/plain", "UTF-8"));
        alternative.addBodyPart(mbp1);
        alternative.addBodyPart(mbp2);
        MimeBodyPart altbody = new MimeBodyPart();
        altbody.setContent(alternative);
        mp.addBodyPart(altbody);
    } else {
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(body, MailUtils.buildPartContentType("text/plain", "UTF-8"));
        mp.addBodyPart(mbp1);
    }

    if (parts != null) {
        for (MimeBodyPart part : parts)
            mp.addBodyPart(part);
    }

    msg.setContent(mp);

    msg.setSentDate(new java.util.Date());

    Transport.send(msg);
}