Example usage for javax.mail Message setSubject

List of usage examples for javax.mail Message setSubject

Introduction

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

Prototype

public abstract void setSubject(String subject) throws MessagingException;

Source Link

Document

Set the subject of this message.

Usage

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

public boolean dispatch(BIObject document, byte[] executionOutput) {
    Map parametersMap;//w  ww . ja v a2s. 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.apache.hupa.server.handler.AbstractFetchMessagesHandler.java

protected ArrayList<org.apache.hupa.shared.data.Message> convert(int offset,
        com.sun.mail.imap.IMAPFolder folder, Message[] messages) throws MessagingException {
    ArrayList<org.apache.hupa.shared.data.Message> mList = new ArrayList<org.apache.hupa.shared.data.Message>();
    // Setup fetchprofile to limit the stuff which is fetched 
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);//from  w w w  . j  a  v a 2  s . c  o  m
    fp.add(FetchProfile.Item.FLAGS);
    fp.add(FetchProfile.Item.CONTENT_INFO);
    fp.add(UIDFolder.FetchProfileItem.UID);
    folder.fetch(messages, fp);

    // loop over the fetched messages
    for (int i = 0; i < messages.length && i < offset; i++) {
        org.apache.hupa.shared.data.Message msg = new org.apache.hupa.shared.data.Message();
        Message m = messages[i];
        String from = null;
        if (m.getFrom() != null && m.getFrom().length > 0) {
            from = MessageUtils.decodeText(m.getFrom()[0].toString());
        }
        msg.setFrom(from);

        String replyto = null;
        if (m.getReplyTo() != null && m.getReplyTo().length > 0) {
            replyto = MessageUtils.decodeText(m.getReplyTo()[0].toString());
        }
        msg.setReplyto(replyto);

        ArrayList<String> to = new ArrayList<String>();
        // Add to addresses
        Address[] toArray = m.getRecipients(RecipientType.TO);
        if (toArray != null) {
            for (Address addr : toArray) {
                String mailTo = MessageUtils.decodeText(addr.toString());
                to.add(mailTo);
            }
        }
        msg.setTo(to);

        // Check if a subject exist and if so decode it
        String subject = m.getSubject();
        if (subject != null) {
            subject = MessageUtils.decodeText(subject);
        }
        msg.setSubject(subject);

        // Add cc addresses
        Address[] ccArray = m.getRecipients(RecipientType.CC);
        ArrayList<String> cc = new ArrayList<String>();
        if (ccArray != null) {
            for (Address addr : ccArray) {
                String mailCc = MessageUtils.decodeText(addr.toString());
                cc.add(mailCc);
            }
        }
        msg.setCc(cc);

        userPreferences.addContact(from);
        userPreferences.addContact(to);
        userPreferences.addContact(replyto);
        userPreferences.addContact(cc);

        // Using sentDate since received date is not useful in the view when using fetchmail
        msg.setReceivedDate(m.getSentDate());

        // Add flags
        ArrayList<IMAPFlag> iFlags = JavamailUtil.convert(m.getFlags());

        ArrayList<Tag> tags = new ArrayList<Tag>();
        for (String flag : m.getFlags().getUserFlags()) {
            if (flag.startsWith(Tag.PREFIX)) {
                tags.add(new Tag(flag.substring(Tag.PREFIX.length())));
            }
        }

        msg.setUid(folder.getUID(m));
        msg.setFlags(iFlags);
        msg.setTags(tags);
        try {
            msg.setHasAttachments(hasAttachment(m));
        } catch (MessagingException e) {
            logger.debug("Unable to identify attachments in message UID:" + msg.getUid() + " subject:"
                    + msg.getSubject() + " cause:" + e.getMessage());
            logger.info("");
        }
        mList.add(0, msg);

    }
    return mList;
}

From source file:GUI.DashbordAdminFrame.java

private void btnEnvMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnvMailActionPerformed
    // TODO add your handling code here:
    String to = null;//from  ww  w .ja va2  s  .  com
    UserDao u = new UserDao();
    List listeTo = new ArrayList();
    listeTo = u.findAllEmail();

    String from = "allfordealpi@gmail.com";
    final String username = "allfordealpi@gmail.com";
    final String password = "pidev2016";

    String host = "smtp.gmail.com";

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

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {

        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        for (Object o : listeTo) {

            to = (String) o;
            System.out.println(to);
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

            message.setSubject(tfObjet.getText());

            message.setText(taContenu.getText());

            // Send message
            Transport.send(message);
        }
        System.out.println("Sent message successfully....");

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

}

From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java

@Override
public void send(List<String> to, List<String> cc, List<String> bcc, String subject, String body,
        List<NodeRef> attachments, boolean html) throws Exception {
    EmailConfig config = getConfig();// ww w . j  a  v a2  s . c om
    EmailProvider provider = getEmailProvider(config.getProviderId());
    Properties props = System.getProperties();
    String prefix = "mail." + provider.getOutgoingProto() + ".";
    props.put(prefix + "host", provider.getOutgoingServer());
    props.put(prefix + "port", provider.getOutgoingPort());
    props.put(prefix + "auth", "true");
    Session session = Session.getInstance(props, null);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(config.getAddress(), config.getRealName()));
    if (to != null) {
        InternetAddress[] recipients = new InternetAddress[to.size()];
        for (int i = 0; i < to.size(); i++)
            recipients[i] = new InternetAddress(to.get(i));
        msg.setRecipients(Message.RecipientType.TO, recipients);
    }

    if (cc != null) {
        InternetAddress[] recipients = new InternetAddress[cc.size()];
        for (int i = 0; i < cc.size(); i++)
            recipients[i] = new InternetAddress(cc.get(i));
        msg.setRecipients(Message.RecipientType.CC, recipients);
    }

    if (bcc != null) {
        InternetAddress[] recipients = new InternetAddress[bcc.size()];
        for (int i = 0; i < bcc.size(); i++)
            recipients[i] = new InternetAddress(bcc.get(i));
        msg.setRecipients(Message.RecipientType.BCC, recipients);
    }

    msg.setSubject(subject);
    msg.setHeader("X-Mailer", "Alvex Emailer");
    msg.setSentDate(new Date());

    MimeBodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();

    if (body != null) {
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body, "utf-8", html ? "html" : "plain");
        multipart.addBodyPart(messageBodyPart);
    }

    if (attachments != null)
        for (NodeRef att : attachments) {
            messageBodyPart = new MimeBodyPart();
            String fileName = (String) nodeService.getProperty(att, AlvexContentModel.PROP_EMAIL_REAL_NAME);
            messageBodyPart
                    .setDataHandler(new DataHandler(new RepositoryDataSource(att, fileName, contentService)));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        }

    msg.setContent(multipart);

    SMTPTransport t = (SMTPTransport) session.getTransport(provider.getOutgoingProto());
    t.connect(config.getUsername(), config.getPassword());
    t.sendMessage(msg, msg.getAllRecipients());
    t.close();
}

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   w  w w . j  a v a 2s. c o m
    }

    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:smilehouse.opensyncro.pipes.Pipe.java

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

    logEntry.setStatusCode(statusCode);// ww w .  j av a  2 s . c o m
    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: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 {/*  w  ww .ja  v  a  2  s  .  co m*/

        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:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java

private void sendToDl(DispatchContext sInfo, BIObject biobj, byte[] response, String retCT, String fileExt,
        String toBeAppendedToName, String toBeAppendedToDescription) {
    logger.debug("IN");
    try {// w  w  w.ja  v a2 s  .co  m

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        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(""))
            throw new Exception("Smtp user not configured");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");
        if ((pass == null) || pass.trim().equals(""))
            throw new Exception("Smtp password not configured");

        String mailTos = "";
        List dlIds = sInfo.getDlIds();
        Iterator it = dlIds.iterator();
        while (it.hasNext()) {

            Integer dlId = (Integer) it.next();
            DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);

            List emails = new ArrayList();
            emails = dl.getEmails();
            Iterator j = emails.iterator();
            while (j.hasNext()) {
                Email e = (Email) j.next();
                String email = e.getEmail();
                String userTemp = e.getUserId();
                IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
                if (ObjectsAccessVerifier.canSee(biobj, userProfile)) {
                    if (j.hasNext()) {
                        mailTos = mailTos + email + ",";
                    } else {
                        mailTos = mailTos + email;
                    }
                }

            }
        }

        if ((mailTos == null) || mailTos.trim().equals("")) {
            throw new Exception("No recipient address found");
        }

        String[] recipients = mailTos.split(",");
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.auth", "true");
        // create autheticator object
        Authenticator auth = new SMTPAuthenticator(user, pass);
        // open session
        Session session = Session.getDefaultInstance(props, auth);
        // 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
        IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
        String subject = biobj.getName() + toBeAppendedToName;
        msg.setSubject(subject);
        // create and fill the first message part
        //MimeBodyPart mbp1 = new MimeBodyPart();
        //mbp1.setText(mailTxt);
        // 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:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java

private void sendEmail(SmtpMessage msg) throws MessagingException {
    Properties props = new Properties();
    boolean doAuth = false;
    props.setProperty("mail.smtp.host", prov.getSmtpHost());
    props.setProperty("mail.smtp.port", Integer.toString(prov.getSmtpPort()));
    if (prov.getSmtpUser() != null && !prov.getSmtpUser().isEmpty()) {
        logger.debug("SMTP user found '" + prov.getSmtpUser() + "', enabling authentication");
        props.setProperty("mail.smtp.user", prov.getSmtpUser());
        props.setProperty("mail.smtp.auth", "true");
        doAuth = true;//from   ww  w  . ja  va2s . c om
    } else {
        logger.debug("No SMTP user, disabling authentication");
        doAuth = false;
        props.setProperty("mail.smtp.auth", "false");
    }
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.smtp.starttls.enable", Boolean.toString(prov.isSmtpTLS()));
    if (logger.isDebugEnabled()) {
        props.setProperty("mail.debug", "true");
        props.setProperty("mail.socket.debug", "true");
    }

    if (prov.getLocalhost() != null && !prov.getLocalhost().isEmpty()) {
        props.setProperty("mail.smtp.localhost", prov.getLocalhost());
    }

    if (prov.isUseSOCKSProxy()) {

        props.setProperty("mail.smtp.socks.host", prov.getSocksProxyHost());

        props.setProperty("mail.smtp.socks.port", Integer.toString(prov.getSocksProxyPort()));
        props.setProperty("mail.smtps.socks.host", prov.getSocksProxyHost());

        props.setProperty("mail.smtps.socks.port", Integer.toString(prov.getSocksProxyPort()));
    }

    //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword));

    Session session = null;
    if (doAuth) {
        logger.debug("Creating authenticated session");
        session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(prov.getSmtpUser(), prov.getSmtpPassword());
            }
        });
    } else {
        logger.debug("Creating unauthenticated session");
        session = Session.getInstance(props);
    }
    if (logger.isDebugEnabled()) {
        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);

    if (msg.contentType != null) {
        msgToSend.setContent(msg.msg, msg.contentType);
    } else {
        msgToSend.setText(msg.msg);
    }

    msgToSend.saveChanges();
    Transport.send(msgToSend);

    //tr.sendMessage(msg, msg.getAllRecipients());
    //tr.close();
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static void sendMail(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {

    boolean debug = false;

    // Arguments:
    // String smtp, String from, String recipients[ ], String subject, String message 
    if (ArgList.length == 5) {

        try {/*from   w ww . j  ava2  s .co m*/
            //Set the host smtp address
            Properties props = new Properties();
            props.put("mail.smtp.host", ArgList[0]);

            // create some properties and get the default Session
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);

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

            // set the from and to address
            InternetAddress addressFrom = new InternetAddress((String) ArgList[1]);
            msg.setFrom(addressFrom);

            // Get Recipients
            String strArrRecipients[] = ((String) ArgList[2]).split(",");

            InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length];
            for (int i = 0; i < strArrRecipients.length; i++) {
                addressTo[i] = new InternetAddress(strArrRecipients[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, addressTo);

            // Optional : You can also set your custom headers in the Email if you Want
            msg.addHeader("MyHeaderName", "myHeaderValue");

            // Setting the Subject and Content Type
            msg.setSubject((String) ArgList[3]);
            msg.setContent((String) ArgList[4], "text/plain");
            Transport.send(msg);
        } catch (Exception e) {
            throw new RuntimeException("sendMail: " + e.toString());
        }
    } else {
        throw new RuntimeException("The function call sendMail requires 5 arguments.");
    }
}