Example usage for javax.mail Message setSentDate

List of usage examples for javax.mail Message setSentDate

Introduction

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

Prototype

public abstract void setSentDate(Date date) throws MessagingException;

Source Link

Document

Set the sent date of this message.

Usage

From source file:com.quinsoft.zeidon.zeidonoperations.ZDRVROPR.java

public int CreateSeeMessage(int lConnection, String szSMTPServer, String szUserEmailAddress,
        String szRecipientEmailAddress, String szCCAddress, String szBCCAddress, String szSubjectText,
        int MimeType, String szMessageBody, String string4, String string5, int attachmentFlag,
        String szAttachmentFileName, String szUserEmailName, String szUserEmailPassword) {
    InternetAddress fromAddress = null;//w ww .j a  v  a 2  s  .co  m
    String host = szSMTPServer; //enc-exhub.enc-ad.enc.edu
    String from = szUserEmailAddress;
    String to[] = szRecipientEmailAddress.split("[\\s,;]+");
    InternetAddress[] toAddress = new InternetAddress[to.length];
    String cc[] = szCCAddress.split("[\\s,;]+");
    InternetAddress[] ccAddress = new InternetAddress[cc.length];
    String bcc[] = szBCCAddress.split("[\\s,;]+");
    InternetAddress[] bccAddress = new InternetAddress[bcc.length];
    //String host = "enc-exhub.enc-ad.enc.edu";
    //String from = "kellysautter@comcast.net";
    //String to = "kellysautter@comcast.net";

    // Set properties
    Properties props = new Properties();
    //mail.smtp.sendpartial
    props.put("mail.smtp.host", host);
    props.put("mail.debug", "true");

    // Get session
    // Going to use getDefaultInstance
    // If I get java.lang.SecurityException: Access to default session denied
    // then it said to go use .getInstance(props).
    Session session = Session.getDefaultInstance(props);

    try {
        // Instantiate a message
        Message msg = new MimeMessage(session);

        try {
            if (from != null && !from.isEmpty())
                fromAddress = new InternetAddress(from);
            if (szRecipientEmailAddress != null && !szRecipientEmailAddress.isEmpty()) {
                for (int iCnt = 0; iCnt < to.length; iCnt++) {
                    toAddress[iCnt] = new InternetAddress(to[iCnt]);
                }
            }
            if (szCCAddress != null && !szCCAddress.isEmpty()) {
                for (int iCnt = 0; iCnt < cc.length; iCnt++) {
                    ccAddress[iCnt] = new InternetAddress(cc[iCnt]);
                }
            }
            if (szBCCAddress != null && !szBCCAddress.isEmpty()) {
                for (int iCnt = 0; iCnt < bcc.length; iCnt++) {
                    bccAddress[iCnt] = new InternetAddress(bcc[iCnt]);
                }
            }
        } catch (AddressException e) {
            task.log().error("*** CreateSeeMessage: setting addresses **** ");
            task.log().error(e);
            return -1;
        }
        // Set the FROM message
        msg.setFrom(fromAddress);

        if (szRecipientEmailAddress != null && !szRecipientEmailAddress.isEmpty())
            msg.setRecipients(Message.RecipientType.TO, toAddress);
        if (szCCAddress != null && !szCCAddress.isEmpty())
            msg.setRecipients(Message.RecipientType.CC, ccAddress);
        if (szBCCAddress != null && !szBCCAddress.isEmpty())
            msg.setRecipients(Message.RecipientType.BCC, bccAddress);

        // Set the message subject and date we sent it.
        msg.setSubject(szSubjectText);
        msg.setSentDate(new Date());

        // Set message content
        msg.setText(szMessageBody);

        // Send the message
        Transport.send(msg);
    } catch (MessagingException mex) {
        task.log().error("*** CreateSeeMessage: Transport.send error ****  ");
        task.log().error(mex);
        // Email was bad?
        if (mex instanceof SendFailedException)
            return -1;

        // SMTP connection bad?
        return -2;
    }

    return 0;
}

From source file:com.panet.imeta.job.entries.mail.JobEntryMail.java

public Result execute(Result result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();

    File masterZipfile = null;/*  ww  w. j a va2s .  c o  m*/

    // Send an e-mail...
    // create some properties and get the default Session
    Properties props = new Properties();
    if (Const.isEmpty(server)) {
        log.logError(toString(), Messages.getString("JobMail.Error.HostNotSpecified"));

        result.setNrErrors(1L);
        result.setResult(false);
        return result;
    }

    String protocol = "smtp";
    if (usingSecureAuthentication) {
        if (secureConnectionType.equals("TLS")) {
            // Allow TLS authentication
            props.put("mail.smtp.starttls.enable", "true");
        } else {

            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version
            // Unknown
            props.put("mail.smtps.quitwait", "false");
        }

    }

    props.put("mail." + protocol + ".host", environmentSubstitute(server));
    if (!Const.isEmpty(port))
        props.put("mail." + protocol + ".port", environmentSubstitute(port));
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        props.put("mail.debug", "true");

    if (usingAuthentication) {
        props.put("mail." + protocol + ".auth", "true");

        /*
         * authenticator = new Authenticator() { protected
         * PasswordAuthentication getPasswordAuthentication() { return new
         * PasswordAuthentication(
         * StringUtil.environmentSubstitute(Const.NVL(authenticationUser,
         * "")),
         * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword
         * , "")) ); } };
         */
    }

    Session session = Session.getInstance(props);
    session.setDebug(debug);

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

        // set message priority
        if (usePriority) {
            String priority_int = "1";
            if (priority.equals("low")) {
                priority_int = "3";
            }
            if (priority.equals("normal")) {
                priority_int = "2";
            }

            msg.setHeader("X-Priority", priority_int); // (String)int
            // between 1= high
            // and 3 = low.
            msg.setHeader("Importance", importance);
            // seems to be needed for MS Outlook.
            // where it returns a string of high /normal /low.
        }

        // Set Mail sender (From)
        String sender_address = environmentSubstitute(replyAddress);
        if (!Const.isEmpty(sender_address)) {
            String sender_name = environmentSubstitute(replyName);
            if (!Const.isEmpty(sender_name))
                sender_address = sender_name + '<' + sender_address + '>';
            msg.setFrom(new InternetAddress(sender_address));
        } else {
            throw new MessagingException(Messages.getString("JobMail.Error.ReplyEmailNotFilled"));
        }

        // set Reply to addresses
        String reply_to_address = environmentSubstitute(replyToAddresses);
        if (!Const.isEmpty(reply_to_address)) {
            // Split the mail-address: space separated
            String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" ");
            InternetAddress[] address = new InternetAddress[reply_Address_List.length];
            for (int i = 0; i < reply_Address_List.length; i++)
                address[i] = new InternetAddress(reply_Address_List[i]);
            msg.setReplyTo(address);
        }

        // Split the mail-address: space separated
        String destinations[] = environmentSubstitute(destination).split(" ");
        InternetAddress[] address = new InternetAddress[destinations.length];
        for (int i = 0; i < destinations.length; i++)
            address[i] = new InternetAddress(destinations[i]);
        msg.setRecipients(Message.RecipientType.TO, address);

        if (!Const.isEmpty(destinationCc)) {
            // Split the mail-address Cc: space separated
            String destinationsCc[] = environmentSubstitute(destinationCc).split(" ");
            InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
            for (int i = 0; i < destinationsCc.length; i++)
                addressCc[i] = new InternetAddress(destinationsCc[i]);

            msg.setRecipients(Message.RecipientType.CC, addressCc);
        }

        if (!Const.isEmpty(destinationBCc)) {
            // Split the mail-address BCc: space separated
            String destinationsBCc[] = environmentSubstitute(destinationBCc).split(" ");
            InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
            for (int i = 0; i < destinationsBCc.length; i++)
                addressBCc[i] = new InternetAddress(destinationsBCc[i]);

            msg.setRecipients(Message.RecipientType.BCC, addressBCc);
        }
        String realSubject = environmentSubstitute(subject);
        if (!Const.isEmpty(realSubject)) {
            msg.setSubject(realSubject);
        }

        msg.setSentDate(new Date());
        StringBuffer messageText = new StringBuffer();

        if (comment != null) {
            messageText.append(environmentSubstitute(comment)).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment) {

            messageText.append(Messages.getString("JobMail.Log.Comment.Job")).append(Const.CR);
            messageText.append("-----").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobName") + "    : ")
                    .append(parentJob.getJobMeta().getName()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobDirectory") + "  : ")
                    .append(parentJob.getJobMeta().getDirectory()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobEntry") + "   : ").append(getName())
                    .append(Const.CR);
            messageText.append(Const.CR);
        }

        if (includeDate) {
            messageText.append(Const.CR).append(Messages.getString("JobMail.Log.Comment.MsgDate") + ": ")
                    .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);
        }
        if (!onlySendComment && result != null) {
            messageText.append(Messages.getString("JobMail.Log.Comment.PreviousResult") + ":").append(Const.CR);
            messageText.append("-----------------").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.JobEntryNr") + "         : ")
                    .append(result.getEntryNr()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Errors") + "               : ")
                    .append(result.getNrErrors()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesRead") + "           : ")
                    .append(result.getNrLinesRead()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesWritten") + "        : ")
                    .append(result.getNrLinesWritten()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesInput") + "          : ")
                    .append(result.getNrLinesInput()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesOutput") + "         : ")
                    .append(result.getNrLinesOutput()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.LinesUpdated") + "        : ")
                    .append(result.getNrLinesUpdated()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Status") + "  : ")
                    .append(result.getExitStatus()).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Result") + "               : ")
                    .append(result.getResult()).append(Const.CR);
            messageText.append(Const.CR);
        }

        if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson))
                || !Const.isEmpty(environmentSubstitute(contactPhone)))) {
            messageText.append(Messages.getString("JobMail.Log.Comment.ContactInfo") + " :").append(Const.CR);
            messageText.append("---------------------").append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.PersonToContact") + " : ")
                    .append(environmentSubstitute(contactPerson)).append(Const.CR);
            messageText.append(Messages.getString("JobMail.Log.Comment.Tel") + "  : ")
                    .append(environmentSubstitute(contactPhone)).append(Const.CR);
            messageText.append(Const.CR);
        }

        // Include the path to this job entry...
        if (!onlySendComment) {
            JobTracker jobTracker = parentJob.getJobTracker();
            if (jobTracker != null) {
                messageText.append(Messages.getString("JobMail.Log.Comment.PathToJobentry") + ":")
                        .append(Const.CR);
                messageText.append("------------------------").append(Const.CR);

                addBacktracking(jobTracker, messageText);
            }
        }

        Multipart parts = new MimeMultipart();
        MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
        // 1st part

        if (useHTML) {
            if (!Const.isEmpty(getEncoding())) {
                part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding());
            } else {
                part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
            }

        }

        else
            part1.setText(messageText.toString());

        parts.addBodyPart(part1);

        if (includingFiles && result != null) {
            List<ResultFile> resultFiles = result.getResultFilesList();
            if (resultFiles != null && !resultFiles.isEmpty()) {
                if (!zipFiles) {
                    // Add all files to the message...
                    //
                    for (ResultFile resultFile : resultFiles) {
                        FileObject file = resultFile.getFile();
                        if (file != null && file.exists()) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                // create a data source
                                MimeBodyPart files = new MimeBodyPart();
                                URLDataSource fds = new URLDataSource(file.getURL());

                                // get a data Handler to manipulate this
                                // file type;
                                files.setDataHandler(new DataHandler(fds));
                                // include the file in the data source
                                files.setFileName(file.getName().getBaseName());
                                // add the part with the file in the
                                // BodyPart();
                                parts.addBodyPart(files);

                                log.logBasic(toString(),
                                        "Added file '" + fds.getName() + "' to the mail message.");
                            }
                        }
                    }
                } else {
                    // create a single ZIP archive of all files
                    masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR
                            + environmentSubstitute(zipFilename));
                    ZipOutputStream zipOutputStream = null;
                    try {
                        zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile));

                        for (ResultFile resultFile : resultFiles) {
                            boolean found = false;
                            for (int i = 0; i < fileType.length; i++) {
                                if (fileType[i] == resultFile.getType())
                                    found = true;
                            }
                            if (found) {
                                FileObject file = resultFile.getFile();
                                ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName());
                                zipOutputStream.putNextEntry(zipEntry);

                                // Now put the content of this file into
                                // this archive...
                                BufferedInputStream inputStream = new BufferedInputStream(
                                        KettleVFS.getInputStream(file));
                                int c;
                                while ((c = inputStream.read()) >= 0) {
                                    zipOutputStream.write(c);
                                }
                                inputStream.close();
                                zipOutputStream.closeEntry();

                                log.logBasic(toString(), "Added file '" + file.getName().getURI()
                                        + "' to the mail message in a zip archive.");
                            }
                        }
                    } catch (Exception e) {
                        log.logError(toString(), "Error zipping attachement files into file ["
                                + masterZipfile.getPath() + "] : " + e.toString());
                        log.logError(toString(), Const.getStackTracker(e));
                        result.setNrErrors(1);
                    } finally {
                        if (zipOutputStream != null) {
                            try {
                                zipOutputStream.finish();
                                zipOutputStream.close();
                            } catch (IOException e) {
                                log.logError(toString(),
                                        "Unable to close attachement zip file archive : " + e.toString());
                                log.logError(toString(), Const.getStackTracker(e));
                                result.setNrErrors(1);
                            }
                        }
                    }

                    // Now attach the master zip file to the message.
                    if (result.getNrErrors() == 0) {
                        // create a data source
                        MimeBodyPart files = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(masterZipfile);
                        // get a data Handler to manipulate this file type;
                        files.setDataHandler(new DataHandler(fds));
                        // include the file in th e data source
                        files.setFileName(fds.getName());
                        // add the part with the file in the BodyPart();
                        parts.addBodyPart(files);
                    }
                }
            }
        }
        msg.setContent(parts);

        Transport transport = null;
        try {
            transport = session.getTransport(protocol);
            if (usingAuthentication) {
                if (!Const.isEmpty(port)) {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))),
                            environmentSubstitute(Const.NVL(authenticationUser, "")),
                            environmentSubstitute(Const.NVL(authenticationPassword, "")));
                } else {
                    transport.connect(environmentSubstitute(Const.NVL(server, "")),
                            environmentSubstitute(Const.NVL(authenticationUser, "")),
                            environmentSubstitute(Const.NVL(authenticationPassword, "")));
                }
            } else {
                transport.connect();
            }
            transport.sendMessage(msg, msg.getAllRecipients());
        } finally {
            if (transport != null)
                transport.close();
        }
    } catch (IOException e) {
        log.logError(toString(), "Problem while sending message: " + e.toString());
        result.setNrErrors(1);
    } catch (MessagingException mex) {
        log.logError(toString(), "Problem while sending message: " + mex.toString());
        result.setNrErrors(1);

        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;

                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    log.logError(toString(), "    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++) {
                        log.logError(toString(), "         " + invalid[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    log.logError(toString(), "    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++) {
                        log.logError(toString(), "         " + validUnsent[i]);
                        result.setNrErrors(1);
                    }
                }

                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    // System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++) {
                        log.logError(toString(), "         " + validSent[i]);
                        result.setNrErrors(1);
                    }
                }
            }
            if (ex instanceof MessagingException) {
                ex = ((MessagingException) ex).getNextException();
            } else {
                ex = null;
            }
        } while (ex != null);
    } finally {
        if (masterZipfile != null && masterZipfile.exists()) {
            masterZipfile.delete();
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }

    return result;
}

From source file:de.innovationgate.wgpublisher.WGACore.java

public void send(WGAMailNotification notification) {
    WGAMailConfiguration config = getMailConfig();

    if (config != null && config.isEnableAdminNotifications()) {
        try {//from  w  w  w .  java2s  .co m
            Message msg = new MimeMessage(config.createMailSession());

            // set recipient and from address
            String toAddress = config.getToAddress();
            if (toAddress == null) {
                getLog().error(
                        "Unable to send wga admin notification because no recipient address is configured");
                return;
            }

            msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
            InternetAddress[] fromAddr = new InternetAddress[1];
            fromAddr[0] = new InternetAddress(config.getFromAddress());
            msg.addFrom(fromAddr);

            msg.setSentDate(new Date());

            InetAddress localMachine = InetAddress.getLocalHost();
            String hostname = localMachine.getHostName();
            String serverName = getWgaConfiguration().getServerName();
            if (serverName == null) {
                serverName = hostname;
            }

            msg.setSubject(notification.getSubject());

            msg.setHeader(WGAMailNotification.HEADERFIELD_TYPE, notification.getType());

            MimeMultipart content = new MimeMultipart();
            MimeBodyPart body = new MimeBodyPart();

            StringBuffer strBody = new StringBuffer();
            strBody.append("<html><head></head><body style=\"color:#808080\">");
            strBody.append(notification.getMessage());
            String rootURL = getWgaConfiguration().getRootURL();
            if (rootURL != null) {
                //strBody.append("<br><br>");
                strBody.append("<p><a href=\"" + rootURL + "/plugin-admin\">" + WGABrand.getName()
                        + " admin client ...</a></p>");
            }
            // append footer
            strBody.append("<br><br><b>System information:</b><br><br>");
            strBody.append("<b>Server:</b> " + serverName + " / " + WGACore.getReleaseString() + "<br>");
            strBody.append("<b>Host:</b> " + hostname + "<br>");
            strBody.append("<b>Operation System:</b> " + System.getProperty("os.name") + " Version "
                    + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ")<br>");
            strBody.append("<b>Java virtual machine:</b> " + System.getProperty("java.vm.name") + " Version "
                    + System.getProperty("java.vm.version") + " (" + System.getProperty("java.vm.vendor")
                    + ")");

            strBody.append("</body></html>");
            body.setText(strBody.toString());
            body.setHeader("MIME-Version", "1.0");
            body.setHeader("Content-Type", "text/html");

            content.addBodyPart(body);
            AppLog appLog = WGA.get(this).service(AppLog.class);

            if (notification.isAttachLogfile()) {
                MimeBodyPart attachmentBody = new MimeBodyPart();

                StringWriter applog = new StringWriter();
                int applogSize = appLog.getLinesCount();
                int offset = applogSize - notification.getLogfileLines();
                if (offset < 0) {
                    offset = 1;
                }
                appLog.writePage(offset, notification.getLogfileLines(), applog, LogLevel.LEVEL_INFO, false);

                attachmentBody.setDataHandler(new DataHandler(applog.toString(), "text/plain"));
                attachmentBody.setFileName("wga.log");
                content.addBodyPart(attachmentBody);
            }
            msg.setContent(content);

            // Send mail
            Thread mailThread = new Thread(new AsyncMailSender(msg), "WGAMailSender");
            mailThread.start();
        } catch (Exception e) {
            getLog().error("Unable to send wga admin notification.", e);
        }
    }
}

From source file:org.apache.nifi.processors.standard.PutEmail.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;// w w  w.j ava2s. c om
    }

    final Properties properties = this.getMailPropertiesFromFlowFile(context, flowFile);

    final Session mailSession = this.createMailSession(properties);

    final Message message = new MimeMessage(mailSession);
    final ComponentLog logger = getLogger();

    try {
        message.addFrom(toInetAddresses(context, flowFile, FROM));
        message.setRecipients(RecipientType.TO, toInetAddresses(context, flowFile, TO));
        message.setRecipients(RecipientType.CC, toInetAddresses(context, flowFile, CC));
        message.setRecipients(RecipientType.BCC, toInetAddresses(context, flowFile, BCC));

        message.setHeader("X-Mailer",
                context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions(flowFile).getValue());
        message.setSubject(context.getProperty(SUBJECT).evaluateAttributeExpressions(flowFile).getValue());
        String messageText = context.getProperty(MESSAGE).evaluateAttributeExpressions(flowFile).getValue();

        if (context.getProperty(INCLUDE_ALL_ATTRIBUTES).asBoolean()) {
            messageText = formatAttributes(flowFile, messageText);
        }

        String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions(flowFile)
                .getValue();
        message.setContent(messageText, contentType);
        message.setSentDate(new Date());

        if (context.getProperty(ATTACH_FILE).asBoolean()) {
            final MimeBodyPart mimeText = new PreencodedMimeBodyPart("base64");
            mimeText.setDataHandler(new DataHandler(new ByteArrayDataSource(
                    Base64.encodeBase64(messageText.getBytes("UTF-8")), contentType + "; charset=\"utf-8\"")));
            final MimeBodyPart mimeFile = new MimeBodyPart();
            session.read(flowFile, new InputStreamCallback() {
                @Override
                public void process(final InputStream stream) throws IOException {
                    try {
                        mimeFile.setDataHandler(
                                new DataHandler(new ByteArrayDataSource(stream, "application/octet-stream")));
                    } catch (final Exception e) {
                        throw new IOException(e);
                    }
                }
            });

            mimeFile.setFileName(flowFile.getAttribute(CoreAttributes.FILENAME.key()));
            MimeMultipart multipart = new MimeMultipart();
            multipart.addBodyPart(mimeText);
            multipart.addBodyPart(mimeFile);
            message.setContent(multipart);
        }

        send(message);

        session.getProvenanceReporter().send(flowFile, "mailto:" + message.getAllRecipients()[0].toString());
        session.transfer(flowFile, REL_SUCCESS);
        logger.info("Sent email as a result of receiving {}", new Object[] { flowFile });
    } catch (final ProcessException | MessagingException | IOException e) {
        context.yield();
        logger.error("Failed to send email for {}: {}; routing to failure",
                new Object[] { flowFile, e.getMessage() }, e);
        session.transfer(flowFile, REL_FAILURE);
    }
}

From source file:org.apache.roller.planet.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type./*from   w w w . j ava2s . c om*/
 * 
 * @param from e-mail address of sender
 * @param to e-mail address(es) of recipients
 * @param subject subject of e-mail
 * @param content the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    Message message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (mLogger.isDebugEnabled())
            mLogger.debug("e-mail from: " + sentFrom);
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("sending e-mail to: " + to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("copying e-mail to: " + cc[i]);
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("blind copying e-mail to: " + bcc[i]);
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject);
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    // Try to send while there remain some potentially good addresses
    do {
        // Avoid a loop if we are stuck
        nAddresses = remainingAddresses.length;

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            Transport.send(message, remainingAddresses);
        } catch (SendFailedException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);

            // Extract the remaining potentially good addresses
            remainingAddresses = ex.getValidUnsentAddresses();
        }
    } while (remainingAddresses != null && remainingAddresses.length > 0
            && remainingAddresses.length != nAddresses);

    if (bFailedToSome)
        throw sendex;
}

From source file:org.apache.roller.weblogger.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type.//www. j a  va  2  s. com
 *
 * @param from e-mail address of sender
 * @param to e-mail address(es) of recipients
 * @param subject subject of e-mail
 * @param content the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(String from, String[] to, String[] cc, String[] bcc, String subject,
        String content, String mimeType) throws MessagingException {

    MailProvider mailProvider = WebloggerStartup.getMailProvider();
    if (mailProvider == null) {
        return;
    }

    Session session = mailProvider.getSession();
    Message message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (log.isDebugEnabled())
            log.debug("e-mail from: " + sentFrom);
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (log.isDebugEnabled())
                log.debug("sending e-mail to: " + to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (log.isDebugEnabled())
                log.debug("copying e-mail to: " + cc[i]);
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (log.isDebugEnabled())
                log.debug("blind copying e-mail to: " + bcc[i]);
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject);
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    Transport transport = mailProvider.getTransport();

    // Try to send while there remain some potentially good addresses
    try {
        do {
            // Avoid a loop if we are stuck
            nAddresses = remainingAddresses.length;

            try {
                // Send to the list of remaining addresses, ignoring the addresses attached to the message
                transport.sendMessage(message, remainingAddresses);
            } catch (SendFailedException ex) {
                bFailedToSome = true;
                sendex.setNextException(ex);

                // Extract the remaining potentially good addresses
                remainingAddresses = ex.getValidUnsentAddresses();
            }
        } while (remainingAddresses != null && remainingAddresses.length > 0
                && remainingAddresses.length != nAddresses);

    } finally {
        transport.close();
    }

    if (bFailedToSome)
        throw sendex;
}

From source file:org.blue.star.plugins.send_mail.java

public boolean execute_check() {

    Properties props = System.getProperties();
    props.put("mail.smtp.host", smtpServer);
    if (smtpAuth) {
        props.put("mail.smtp.auth", "true");
    }// w ww  . j av a 2 s  .  c o m

    Session session = Session.getInstance(props, null);
    SMTPTransport transport = null;
    //      if (debug)
    //         session.setDebug(true);

    // construct the message
    try {
        Message msg = new MimeMessage(session);
        if (from != null)
            msg.setFrom(new InternetAddress(from));
        else
            msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

        if (subject != null)
            msg.setSubject(subject);

        msg.setHeader("X-Mailer", "blue-send-mail");
        msg.setSentDate(new Date());
        msg.setText(message.replace("\\n", "\n").replace("\\t", "\t"));

        transport = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        if (smtpAuth)
            transport.connect(smtpServer, smtpUser, smtpPass);
        else
            transport.connect();
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();

    } catch (MessagingException mE) {
        mE.printStackTrace();
        this.state = common_h.STATE_CRITICAL;
        this.text = mE.getMessage();
        return false;
    } finally {
        try {
            transport.close();
        } catch (Exception e) {
        }
    }

    state = common_h.STATE_OK;
    text = "Message Sent!";
    return true;
}

From source file:org.entermedia.email.PostMail.java

public void postMail(List<InternetAddress> recipients, List<InternetAddress> blindrecipients, String subject,
        String inHtml, String inText, String from, List inAttachments, Map inProperties)
        throws MessagingException {
    // Set the host smtp address
    Properties props = new Properties();
    // create some properties and get the default Session
    props.put("mail.smtp.host", fieldSmtpServer);
    props.put("mail.smtp.port", String.valueOf(getPort()));
    props.put("mail.smtp.auth", new Boolean(fieldSmtpSecured).toString());
    if (isSslEnabled()) {
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }// w w w.  j  a  v  a2s . c  o  m
    Session session = null;
    if (isEnableTls()) {
        props.put("mail.smtp.starttls.enable", "true");
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(getSmtpUsername(), getSmtpPassword());
            }
        });
    } else if (fieldSmtpSecured) {
        SmtpAuthenticator auth = new SmtpAuthenticator();
        session = Session.getInstance(props, auth);
    } else {
        session = Session.getInstance(props);
    }
    // session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);
    MimeMultipart mp = null;
    // msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message,
    // "text/html")));

    if (inAttachments != null && inAttachments.size() == 0) {
        inAttachments = null;
    }

    if (inText != null && inHtml != null || inAttachments != null) {
        // Create an "Alternative" Multipart message
        mp = new MimeMultipart("mixed");

        if (inText != null) {
            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setContent(inText, "text/plain");
            mp.addBodyPart(messageBodyPart);
        }
        if (inHtml != null) {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(inHtml, "text/html");
            mp.addBodyPart(messageBodyPart);
        }
        if (inAttachments != null) {
            for (Iterator iterator = inAttachments.iterator(); iterator.hasNext();) {
                String filename = (String) iterator.next();

                File file = new File(filename);

                if (file.exists() && !file.isDirectory()) {
                    // create the second message part
                    MimeBodyPart mbp = new MimeBodyPart();

                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));

                    mbp.setFileName(fds.getName());

                    mp.addBodyPart(mbp);
                }
            }
        }

        msg.setContent(mp);

    } else if (inHtml != null) {
        msg.setContent(inHtml, "text/html");
    } else {
        msg.setContent(inText, "text/plain");
    }
    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    //msg.setRecipient(RecipientType.BCC, addressFrom);
    msg.setSentDate(new Date());
    if (recipients == null || recipients.isEmpty()) {
        throw new MessagingException("No recipients specified");
    }
    InternetAddress[] addressTo = recipients.toArray(new InternetAddress[recipients.size()]);

    msg.setRecipients(Message.RecipientType.TO, addressTo);

    //add bcc
    if (blindrecipients != null && !blindrecipients.isEmpty()) {
        InternetAddress[] addressBcc = blindrecipients.toArray(new InternetAddress[blindrecipients.size()]);
        msg.setRecipients(Message.RecipientType.BCC, addressBcc);
    }

    // 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(subject);

    // Transport tr = session.getTransport("smtp");
    // tr.connect(serverandport[0], null, null);
    // msg.saveChanges(); // don't forget this
    // tr.sendMessage(msg, msg.getAllRecipients());
    // tr.close();
    // msg.setContent(msg, "text/plain");

    Transport.send(msg);
    log.info("sent email " + subject);
}

From source file:org.fao.geonet.services.register.SelfRegister.java

/**
 * Send an email.// www  . j a va  2s  . c  o  m
 * 
 * @param host
 * @param port
 * @param subject
 * @param from
 * @param to
 * @param content
 * @return
 */
boolean sendMail(String host, int port, String subject, String from, String to, String content) {
    boolean isSendout = false;

    Properties props = new Properties();

    props.put("mail.transport.protocol", PROTOCOL);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.auth", "false");

    Session mailSession = Session.getDefaultInstance(props);

    try {
        Message msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        msg.setSentDate(new Date());
        msg.setSubject(subject);
        // Add content message
        msg.setText(content);
        Transport.send(msg);
        isSendout = true;
    } catch (AddressException e) {
        isSendout = false;
        e.printStackTrace();
    } catch (MessagingException e) {
        isSendout = false;
        e.printStackTrace();
    }
    return isSendout;
}

From source file:org.forumj.email.FJEMail.java

public static void sendMail(String to, String from, String host, String subject, String text)
        throws ConfigurationException, AddressException, MessagingException {
    Properties props = new Properties();
    props.put("mail.smtp.host", host);
    String mailDebug = FJConfiguration.getConfig().getString("mail.debug");
    props.put("mail.debug", mailDebug == null ? "false" : mailDebug);
    Session session = Session.getInstance(props);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    InternetAddress[] address = { new InternetAddress(to) };
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.addHeader("charset", "UTF-8");
    msg.setSubject(subject);//from  w  ww  .j  a v  a  2  s.  c  o  m
    msg.setSentDate(new Date());
    msg.setDataHandler(new DataHandler(new HTMLDataSource(text)));
    Transport.send(msg);
}