Example usage for org.apache.commons.mail MultiPartEmail MultiPartEmail

List of usage examples for org.apache.commons.mail MultiPartEmail MultiPartEmail

Introduction

In this page you can find the example usage for org.apache.commons.mail MultiPartEmail MultiPartEmail.

Prototype

MultiPartEmail

Source Link

Usage

From source file:net.big_oh.postoffice.PostOfficeService.java

public void sendMail(Set<String> toRecipients, String subject, String messageText, Set<File> attachments)
        throws EmailException {

    Duration dur = new Duration(this.getClass());
    logger.info("Begin send email to " + toRecipients.size() + " recipient(s) with " + attachments.size()
            + " attachment(s).");

    // validate the method parameters
    if (toRecipients.isEmpty()) {
        throw new IllegalArgumentException("Cowardly refusing to send an email message with no recipients.");
    }/*  w  w w. j  a  v a  2s  . c o m*/

    // instantiate an email object
    MultiPartEmail email = new MultiPartEmail();

    // establish SMTP end-point details
    email.setHostName(smtpServerHost);
    email.setSSL(transportWithSsl);
    if (transportWithSsl) {
        email.setSslSmtpPort(Integer.toString(smtpServerPort));
    } else {
        email.setSmtpPort(smtpServerPort);
    }

    // establish SMTP authentication details
    if (!StringUtils.isBlank(smtpUserName) && !StringUtils.isBlank(smtpPassword)) {
        email.setAuthentication(smtpUserName, smtpPassword);
    }
    email.setTLS(authenticateWithTls);

    // establish basic email delivery details
    email.setDebug(debug);
    email.setFrom(sendersFromAddress);
    for (String toRecipient : toRecipients) {
        email.addTo(toRecipient);
    }

    // set email content
    email.setSubject(subject);
    email.setMsg(messageText);

    // create attachments to the email
    for (File file : attachments) {

        if (!file.exists()) {
            logger.error("Skipping attachment file that does not exist: " + file.toString());
            continue;
        }

        if (!file.isFile()) {
            logger.error("Skipping attachment file that is not a normal file: " + file.toString());
            continue;
        }

        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(file.getPath());
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setName(file.getName());

        email.attach(attachment);

    }

    // Send message
    email.send();

    dur.stop("Finished sending email to " + toRecipients.size() + " recipient(s)");

}

From source file:com.day.cq.wcm.foundation.forms.impl.MailServlet.java

/**
 * @see org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest, org.apache.sling.api.SlingHttpServletResponse)
 *///from w  ww .ja  v  a  2 s. co m
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    final MailService localService = this.mailService;
    if (ResourceUtil.isNonExistingResource(request.getResource())) {
        logger.debug("Received fake request!");
        response.setStatus(500);
        return;
    }
    final ResourceBundle resBundle = request.getResourceBundle(null);

    final ValueMap values = ResourceUtil.getValueMap(request.getResource());
    final String[] mailTo = values.get(MAILTO_PROPERTY, String[].class);
    int status = 200;
    if (mailTo == null || mailTo.length == 0 || mailTo[0].length() == 0) {
        // this is a sanity check
        logger.error(
                "The mailto configuration is missing in the form begin at " + request.getResource().getPath());

        status = 500;
    } else if (localService == null) {
        logger.error("The mail service is currently not available! Unable to send form mail.");

        status = 500;
    } else {
        try {
            final StringBuilder builder = new StringBuilder();
            builder.append(request.getScheme());
            builder.append("://");
            builder.append(request.getServerName());
            if ((request.getScheme().equals("https") && request.getServerPort() != 443)
                    || (request.getScheme().equals("http") && request.getServerPort() != 80)) {
                builder.append(':');
                builder.append(request.getServerPort());
            }
            builder.append(request.getRequestURI());

            // construct msg
            final StringBuilder buffer = new StringBuilder();
            String text = resBundle.getString("You've received a new form based mail from {0}.");
            text = text.replace("{0}", builder.toString());
            buffer.append(text);
            buffer.append("\n\n");
            buffer.append(resBundle.getString("Values"));
            buffer.append(":\n\n");
            // we sort the names first - we use the order of the form field and
            // append all others at the end (for compatibility)

            // let's get all parameters first and sort them alphabetically!
            final List<String> contentNamesList = new ArrayList<String>();
            final Iterator<String> names = FormsHelper.getContentRequestParameterNames(request);
            while (names.hasNext()) {
                final String name = names.next();
                contentNamesList.add(name);
            }
            Collections.sort(contentNamesList);

            final List<String> namesList = new ArrayList<String>();
            final Iterator<Resource> fields = FormsHelper.getFormElements(request.getResource());
            while (fields.hasNext()) {
                final Resource field = fields.next();
                final FieldDescription[] descs = FieldHelper.getFieldDescriptions(request, field);
                for (final FieldDescription desc : descs) {
                    // remove from content names list
                    contentNamesList.remove(desc.getName());
                    if (!desc.isPrivate()) {
                        namesList.add(desc.getName());
                    }
                }
            }
            namesList.addAll(contentNamesList);

            // now add form fields to message
            // and uploads as attachments
            final List<RequestParameter> attachments = new ArrayList<RequestParameter>();
            for (final String name : namesList) {
                final RequestParameter rp = request.getRequestParameter(name);
                if (rp == null) {
                    //see Bug https://bugs.day.com/bugzilla/show_bug.cgi?id=35744
                    logger.debug("skipping form element {} from mail content because it's not in the request",
                            name);
                } else if (rp.isFormField()) {
                    buffer.append(name);
                    buffer.append(" : \n");
                    final String[] pValues = request.getParameterValues(name);
                    for (final String v : pValues) {
                        buffer.append(v);
                        buffer.append("\n");
                    }
                    buffer.append("\n");
                } else if (rp.getSize() > 0) {
                    attachments.add(rp);

                } else {
                    //ignore
                }
            }
            // if we have attachments we send a multi part, otherwise a simple email
            final Email email;
            if (attachments.size() > 0) {
                buffer.append("\n");
                buffer.append(resBundle.getString("Attachments"));
                buffer.append(":\n");
                final MultiPartEmail mpEmail = new MultiPartEmail();
                email = mpEmail;
                for (final RequestParameter rp : attachments) {
                    final ByteArrayDataSource ea = new ByteArrayDataSource(rp.getInputStream(),
                            rp.getContentType());
                    mpEmail.attach(ea, rp.getFileName(), rp.getFileName());

                    buffer.append("- ");
                    buffer.append(rp.getFileName());
                    buffer.append("\n");
                }
            } else {
                email = new SimpleEmail();
            }

            email.setMsg(buffer.toString());
            // mailto
            for (final String rec : mailTo) {
                email.addTo(rec);
            }
            // cc
            final String[] ccRecs = values.get(CC_PROPERTY, String[].class);
            if (ccRecs != null) {
                for (final String rec : ccRecs) {
                    email.addCc(rec);
                }
            }
            // bcc
            final String[] bccRecs = values.get(BCC_PROPERTY, String[].class);
            if (bccRecs != null) {
                for (final String rec : bccRecs) {
                    email.addBcc(rec);
                }
            }

            // subject and from address
            final String subject = values.get(SUBJECT_PROPERTY, resBundle.getString("Form Mail"));
            email.setSubject(subject);
            final String fromAddress = values.get(FROM_PROPERTY, "");
            if (fromAddress.length() > 0) {
                email.setFrom(fromAddress);
            }
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Sending form activated mail: fromAddress={}, to={}, subject={}, text={}.",
                        new Object[] { fromAddress, mailTo, subject, buffer });
            }
            localService.sendEmail(email);

        } catch (EmailException e) {
            logger.error("Error sending email: " + e.getMessage(), e);
            status = 500;
        }
    }
    // check for redirect
    String redirectTo = request.getParameter(":redirect");
    if (redirectTo != null) {
        int pos = redirectTo.indexOf('?');
        redirectTo = redirectTo + (pos == -1 ? '?' : '&') + "status=" + status;
        response.sendRedirect(redirectTo);
        return;
    }
    if (FormsHelper.isRedirectToReferrer(request)) {
        FormsHelper.redirectToReferrer(request, response,
                Collections.singletonMap("stats", new String[] { String.valueOf(status) }));
        return;
    }
    response.setStatus(status);
}

From source file:br.ufg.reqweb.components.MailBean.java

private void processEmailToStaff(Map<String, List<Map<String, ?>>> messageMap, String reportPath,
        String reportTitle) {//from  www .  j  ava 2 s . com
    for (Entry message : messageMap.entrySet()) {
        JRMapCollectionDataSource dataSource;
        List<TipoRequerimentoEnum> tipoRequerimentoList;
        List<RequerimentoStatusEnum> status;
        Map reportParameters = new HashMap();
        tipoRequerimentoList = Arrays.asList(TipoRequerimentoEnum.values());
        status = Arrays.asList(new RequerimentoStatusEnum[] { RequerimentoStatusEnum.ABERTO,
                RequerimentoStatusEnum.EM_ANDAMENTO });
        for (RequerimentoStatusEnum statusEnum : RequerimentoStatusEnum.values()) {
            reportParameters.put(statusEnum.name(),
                    LocaleBean.getDefaultMessageBundle().getString(statusEnum.getStatus()));
        }
        System.out.println("path: " + reportPath);
        dataSource = new JRMapCollectionDataSource((List<Map<String, ?>>) message.getValue());
        reportParameters.put("TITULO", reportTitle);
        reportParameters.put("MATRICULA", LocaleBean.getDefaultMessageBundle().getString("usuarioMatricula"));
        reportParameters.put("NOME", LocaleBean.getDefaultMessageBundle().getString("discente"));
        reportParameters.put("DOCENTE", LocaleBean.getDefaultMessageBundle().getString("docente"));
        reportParameters.put("DISCIPLINA", LocaleBean.getDefaultMessageBundle().getString("disciplina"));
        reportParameters.put("TURMA", LocaleBean.getDefaultMessageBundle().getString("turma"));
        reportParameters.put("DATA_PROVA", LocaleBean.getDefaultMessageBundle().getString("dataProvaA"));
        reportParameters.put("DATA_REQUERIMENTO",
                LocaleBean.getDefaultMessageBundle().getString("dataCriacao"));
        reportParameters.put("CURSO", LocaleBean.getDefaultMessageBundle().getString("curso"));
        reportParameters.put("REQUERIMENTO", LocaleBean.getDefaultMessageBundle().getString("requerimento"));
        reportParameters.put("STATUS", LocaleBean.getDefaultMessageBundle().getString("status"));
        reportParameters.put("TOTAL", LocaleBean.getDefaultMessageBundle().getString("total"));
        for (TipoRequerimentoEnum tipoRequerimento : tipoRequerimentoList) {
            reportParameters.put(tipoRequerimento.name(), tipoRequerimento.getTipoLocale());
        }
        JasperPrint jrp;
        try {
            jrp = JasperFillManager.fillReport(context.getRealPath(reportPath), reportParameters, dataSource);
            InputStream inputStream = new ByteArrayInputStream(JasperExportManager.exportReportToPdf(jrp));
            MultiPartEmail email = new MultiPartEmail();
            DataSource ds = new ByteArrayDataSource(inputStream, "application/pdf");
            email.attach(ds, "reqweb.pdf", LocaleBean.getDefaultMessageBundle().getString("relatorioDiario"));
            email.setHostName(configDao.getValue("mail.mailHost"));
            email.setSmtpPort(Integer.parseInt(configDao.getValue("mail.smtpPort")));

            String mailSender = configDao.getValue("mail.mailSender");
            String user = configDao.getValue("mail.mailUser");
            String password = configDao.getValue("mail.mailPassword");
            boolean useSSL = Boolean.parseBoolean(configDao.getValue("mail.useSSL"));

            email.setAuthenticator(new DefaultAuthenticator(user, password));
            email.setSSLOnConnect(useSSL);
            email.setFrom(mailSender);
            email.addTo(message.getKey().toString());
            email.setSubject(LocaleBean.getDefaultMessageBundle().getString("subjectMail"));
            String messageBody = String.format("%s\n\n%s",
                    LocaleBean.getDefaultMessageBundle().getString("subjectMail"),
                    LocaleBean.getDefaultMessageBundle().getString("messageMail"));
            email.setMsg(messageBody);
            email.send();
        } catch (IOException | NullPointerException | EmailException | JRException e) {
            System.out.println("erro ao enviar email");
            System.out.println(e);
        }
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

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

    try {/*from  ww  w.  ja  va 2 s  .  co  m*/

        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(filename);
        attachment.setDisposition(EmailAttachment.ATTACHMENT);

        attachment.setDescription("rezultat TC-uri");
        attachment.setName("rezultat TC-uri");

        MultiPartEmail email = new MultiPartEmail();

        email.setHostName("smtp.gmail.com");
        email.setSmtpPort(465);
        //email.setAuthenticator(new DefaultAuthenticator("test@contentspeed.ro", "andaanda"));
        email.setAuthenticator(new DefaultAuthenticator("anda.cristea@contentspeed.ro", "anda.cristea"));
        email.setSSLOnConnect(true);

        email.addBcc(to1);
        email.addBcc(to2);
        email.setFrom(from, "Teste Automate");
        email.setSubject(subject);
        email.setMsg(subject);

        // add the attachment
        //email.attach(attachment);
        StringWriter writer = new StringWriter();
        IOUtils.copy(new FileInputStream(new File(filename)), writer);

        email.setContent(writer.toString(), "text/html");
        email.attach(attachment);

        // send the email
        email.send();
        writer.close();
    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}

From source file:com.duroty.application.mail.manager.SendManager.java

/**
 * DOCUMENT ME!/*from  w w  w .  ja  va  2  s.  c o m*/
 *
 * @param hsession DOCUMENT ME!
 * @param session DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param ideIdint DOCUMENT ME!
 * @param to DOCUMENT ME!
 * @param cc DOCUMENT ME!
 * @param bcc DOCUMENT ME!
 * @param subject DOCUMENT ME!
 * @param body DOCUMENT ME!
 * @param attachments DOCUMENT ME!
 * @param isHtml DOCUMENT ME!
 * @param charset DOCUMENT ME!
 * @param headers DOCUMENT ME!
 * @param priority DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public void saveDraft(org.hibernate.Session hsession, Session session, String repositoryName, int ideIdint,
        String to, String cc, String bcc, String subject, String body, Vector attachments, boolean isHtml,
        String charset, InternetHeaders headers, String priority) throws MailException {
    try {
        if (charset == null) {
            charset = MimeUtility.javaCharset(Charset.defaultCharset().displayName());
        }

        if ((body == null) || body.trim().equals("")) {
            body = " ";
        }

        Email email = null;

        if (isHtml) {
            email = new HtmlEmail();
        } else {
            email = new MultiPartEmail();
        }

        email.setCharset(charset);

        Users user = getUser(hsession, repositoryName);
        Identity identity = getIdentity(hsession, ideIdint, user);

        InternetAddress _returnPath = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _from = new InternetAddress(identity.getIdeEmail(), identity.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identity.getIdeReplyTo(), identity.getIdeName());
        InternetAddress[] _to = MessageUtilities.encodeAddresses(to, null);
        InternetAddress[] _cc = MessageUtilities.encodeAddresses(cc, null);
        InternetAddress[] _bcc = MessageUtilities.encodeAddresses(bcc, null);

        if (_from != null) {
            email.setFrom(_from.getAddress(), _from.getPersonal());
        }

        if (_returnPath != null) {
            email.addHeader("Return-Path", _returnPath.getAddress());
            email.addHeader("Errors-To", _returnPath.getAddress());
            email.addHeader("X-Errors-To", _returnPath.getAddress());
        }

        if (_replyTo != null) {
            email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
        }

        if ((_to != null) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        if ((_cc != null) && (_cc.length > 0)) {
            HashSet aux = new HashSet(_cc.length);
            Collections.addAll(aux, _cc);
            email.setCc(aux);
        }

        if ((_bcc != null) && (_bcc.length > 0)) {
            HashSet aux = new HashSet(_bcc.length);
            Collections.addAll(aux, _bcc);
            email.setBcc(aux);
        }

        email.setSubject(subject);

        Date now = new Date();

        email.setSentDate(now);

        File dir = new File(System.getProperty("user.home") + File.separator + "tmp");
        if (!dir.exists()) {
            dir.mkdir();
        }

        if ((attachments != null) && (attachments.size() > 0)) {
            for (int i = 0; i < attachments.size(); i++) {
                ByteArrayInputStream bais = null;
                FileOutputStream fos = null;

                try {
                    MailPartObj obj = (MailPartObj) attachments.get(i);

                    File file = new File(dir, obj.getName());

                    bais = new ByteArrayInputStream(obj.getAttachent());
                    fos = new FileOutputStream(file);
                    IOUtils.copy(bais, fos);

                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(file.getPath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setDescription("File Attachment: " + file.getName());
                    attachment.setName(file.getName());

                    if (email instanceof MultiPartEmail) {
                        ((MultiPartEmail) email).attach(attachment);
                    }
                } catch (Exception ex) {

                } finally {
                    IOUtils.closeQuietly(bais);
                    IOUtils.closeQuietly(fos);
                }
            }
        }

        if (headers != null) {
            Header xheader;
            Enumeration xe = headers.getAllHeaders();

            for (; xe.hasMoreElements();) {
                xheader = (Header) xe.nextElement();

                if (xheader.getName().equals(RFC2822Headers.IN_REPLY_TO)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                } else if (xheader.getName().equals(RFC2822Headers.REFERENCES)) {
                    email.addHeader(xheader.getName(), xheader.getValue());
                }
            }
        }

        if (priority != null) {
            if (priority.equals("high")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "1");
            } else if (priority.equals("low")) {
                email.addHeader("Importance", priority);
                email.addHeader("X-priority", "5");
            }
        }

        if (email instanceof HtmlEmail) {
            ((HtmlEmail) email).setHtmlMsg(body);
        } else {
            email.setMsg(body);
        }

        email.setMailSession(session);

        email.buildMimeMessage();

        MimeMessage mime = email.getMimeMessage();
        int size = MessageUtilities.getMessageSize(mime);

        if (!controlQuota(hsession, user, size)) {
            throw new MailException("ErrorMessages.mail.quota.exceded");
        }

        messageable.storeDraftMessage(getId(), mime, user);
    } catch (MailException e) {
        throw e;
    } catch (Exception e) {
        throw new MailException(e);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.zuora.api.UsageAdjInvoiceRegenerator.java

public static void main(String[] args) {

    String exportIdPRPC, exportIdII, exportFileIdII, exportFileIdPRPC, queryII, queryPRPC;

    boolean hasArgs = false;
    if (args != null && args.length >= 1) {
        UsageAdjInvoiceRegenerator.PROPERTY_FILE_NAME = args[0];
        hasArgs = true;// w  ww.  ja v  a  2  s  .co m
    }
    AppParamManager.initParameters(hasArgs);
    if (!AppParamManager.TASK_ID.equals("")) {
        try {
            zApiClient = new ApiClient(AppParamManager.API_URL, AppParamManager.USER_NAME,
                    AppParamManager.USER_PASSWORD, AppParamManager.USER_SESSION);

            zApiClient.login();
        } catch (Exception ex) {
            Logger.print(ex);
            Logger.print("RefreshSession - There's exception in the API call.");
        }

        queryPRPC = AppParamManager.PRPCexportQuery;
        queryII = AppParamManager.IIexportQuery;

        exportIdPRPC = zApiClient.createExport(queryPRPC);

        exportIdII = zApiClient.createExport(queryII);

        // ERROR createExport fails
        if (exportIdII == null || exportIdII.equals("")) {
            Logger.print("Error. Failed to create Invoice Item Export");
            //return false;
        }

        // ERROR createExport fails
        if (exportIdPRPC == null || exportIdPRPC.equals("")) {
            Logger.print("Error. Failed to create PRPC export");
            //return false;
        }

        exportFileIdII = zApiClient.getExportFileId(exportIdII);

        if (exportFileIdII == null) {
            Logger.print("Error. Failed to get Invoice Item Export file Id");
            //log.closeLogFile();
            //return false;
        }

        exportFileIdPRPC = zApiClient.getExportFileId(exportIdPRPC);

        if (exportFileIdPRPC == null) {
            Logger.print("Error. Failed to get PRPC Export file Id");
            //log.closeLogFile();
            //return false;
        }
        // get the export file from zuora
        //zApiClient.getFile(exportFileIdII, exportFileIdTI);

        /*
        Logger.print("II export ID: "+exportFileIdII);
        Logger.print("TI export ID: "+exportFileIdTI);
        */

        Logger.print("Opening Export file");

        //Base64 bs64 = new BASE64Encoder();
        /*
        String login = AppParamManager.USER_NAME+":"+AppParamManager.USER_PASSWORD;
        String authorization ="Basic "+ Base64.encodeBase64String(login.getBytes());
        String zendpoint = "";
        */

        String authorization = "";
        //Base64 bs64 = new BASE64Encoder();
        if (AppParamManager.USER_SESSION.isEmpty()) {
            String login = AppParamManager.USER_NAME + ":" + AppParamManager.USER_PASSWORD;
            authorization = "Basic " + Base64.encodeBase64String(login.getBytes());
        } else {
            authorization = "ZSession " + AppParamManager.USER_SESSION;
        }
        String zendpoint = "";

        try {

            /*
            if( AppParamManager.API_URL.contains("api") ){
               //look in api sandbox
               zendpoint = "https://apisandbox.zuora.com/apps/api/file/";
            } else {
               //look in production
               zendpoint = "https://www.zuora.com/apps/api/file/";
            }
            */

            int index = AppParamManager.API_URL.indexOf("apps");
            index = index + 5;
            zendpoint = AppParamManager.API_URL.substring(0, index) + "api/file/";
            Logger.print(zendpoint);

            //zendpoint = AppParamManager.FILE_URL;

            //Start reading Invoice Items

            String zendpointII = zendpoint + exportFileIdII + "/";

            URL url = new URL(zendpointII);
            URLConnection uc = url.openConnection();
            //Logger.print("Opening invoice item file: "+exportFileIdII+" authorization: "+authorization);
            uc.setRequestProperty("Authorization", authorization);

            InputStream content = (InputStream) uc.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(content));
            CSVReader cvsReader = new CSVReader(in);

            List<String[]> batchOfRawDataList = null;

            while ((batchOfRawDataList = cvsReader.parseEntity()) != null) {
                UsageAdjInvoiceRegenerator.readInvoices(batchOfRawDataList, cvsReader.getBatchStartLineNumber(),
                        "InvoiceItem");
            }

            in.close();

            String zenpointPRPC = zendpoint + exportFileIdPRPC + "/";
            url = new URL(zenpointPRPC);
            uc = url.openConnection();
            uc.setRequestProperty("Authorization", authorization);
            content = (InputStream) uc.getInputStream();
            in = new BufferedReader(new InputStreamReader(content));
            cvsReader = new CSVReader(in);

            while ((batchOfRawDataList = cvsReader.parseEntity()) != null) {
                UsageAdjInvoiceRegenerator.readInvoices(batchOfRawDataList, cvsReader.getBatchStartLineNumber(),
                        "PRPCItem");
            }

            in.close();
            Logger.print("start processing values");

            UsageAdjInvoiceRegenerator chargeAdjustment = new UsageAdjInvoiceRegenerator();
            int[] results;
            int totalErrors = 0;
            String emailmsg = "";
            Logger.print("----------------------------------------");
            Logger.print("start creating usages");
            results = zApiClient.createUsageItems(newUsageCollection);
            if (results[1] != 0) {
                emailmsg = (results[0] - results[1]) + "/" + results[0] + " usage creation ";
            }
            totalErrors = totalErrors + results[1];

            Logger.print("start cancelling invoices");
            results = zApiClient.alterInvoices(newUsageCollection, "cancel");
            if (results[1] != 0) {
                emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice cancellation ";
            }
            totalErrors = totalErrors + results[1];

            Logger.print("start deleting usages");
            results = zApiClient.deleteUsageItems(deleteList);
            if (results[1] != 0) {
                emailmsg = (results[0] - results[1]) + "/" + results[0] + " usage deletion ";
            }
            totalErrors = totalErrors + results[1];

            Logger.print("start regenerating invoices");
            results = zApiClient.alterInvoices(newUsageCollection, "generate");
            if (results[1] != 0) {
                emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice generation ";
            }
            totalErrors = totalErrors + results[1];

            Logger.print("start deleting old invoices");
            results = zApiClient.alterInvoices(newUsageCollection, "delete");
            if (results[1] != 0) {
                emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice deletion ";
            }
            totalErrors = totalErrors + results[1];

            // Create the attachment
            EmailAttachment attachment = new EmailAttachment();
            if (totalErrors > 0) {

                String logFileName = AppParamManager.OUTPUT_FOLDER_LOCATION + File.separator + "runtime_log_"
                        + AppParamManager.OUTPUT_FILE_POSTFIX + ".txt";

                attachment.setPath(logFileName);
                attachment.setDisposition(EmailAttachment.ATTACHMENT);
                attachment.setDescription("System Log");
                attachment.setName("System Log");
            }

            MultiPartEmail email = new MultiPartEmail();
            email.setSmtpPort(587);
            email.setAuthenticator(
                    new DefaultAuthenticator(AppParamManager.EMAIL_ADDRESS, AppParamManager.EMAIL_PASSWORD));
            email.setDebug(false);
            email.setHostName("smtp.gmail.com");
            email.setFrom("zuora@gmail.com");

            if (totalErrors > 0) {
                email.setSubject("Base Calc Processor Finished with Errors");
                email.setMsg("The base calc processing has finished " + emailmsg + "records successfully.");
            } else {
                email.setSubject("Base Calc Processor Finished Successfully");
                emailmsg = (results[0] - results[1]) + "/" + results[0] + " invoice ";
                email.setMsg("The base calc processing has finished " + emailmsg + "records successfully.");
            }
            email.setTLS(true);
            email.addTo(AppParamManager.RECIPIENT_ADDRESS);
            if (totalErrors > 0) {
                email.attach(attachment);
            }
            email.send();
            System.out.println("Mail sent!");
            if (hasArgs) {
                Connection conn = AppParamManager.getConnection();
                Statement stmt = conn.createStatement();
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                java.util.Date date = new Date();
                stmt.executeUpdate("UPDATE TASK SET STATUS = 'completed', END_TIME = '"
                        + dateFormat.format(date) + "' WHERE ID = " + AppParamManager.TASK_ID);
                Utility.saveLogToDB(conn);
                conn.close();
            }

        } catch (Exception e) {
            Logger.print("Failure, gettingFile.");
            Logger.print("Error getting the export file: " + e.getMessage());
            //System.out.println("Error getting the export file: "+e.getMessage());
            try {
                Connection conn = AppParamManager.getConnection();
                Statement stmt = conn.createStatement();
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                java.util.Date date = new Date();
                stmt.executeUpdate("UPDATE TASK SET STATUS = 'failed', END_TIME = '" + dateFormat.format(date)
                        + "' WHERE ID = " + AppParamManager.TASK_ID);
                Utility.saveLogToDB(conn);
                conn.close();
            } catch (Exception e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
        }
    } else {
        Logger.print("No tasks in wait status");
    }
}

From source file:com.googlecode.fascinator.portal.process.EmailNotifier.java

public boolean emailAttachment(String from, String recipient, String subject, String body, byte[] attachData,
        String attachDataType, String attachFileName, String attachDesc) throws Exception {
    MultiPartEmail email = new MultiPartEmail();
    email.attach(new ByteArrayDataSource(attachData, attachDataType), attachFileName, attachDesc,
            EmailAttachment.ATTACHMENT);
    log.debug("Email host: " + host);
    log.debug("Email port: " + port);
    log.debug("Email username: " + username);
    log.debug("Email from: " + from);
    log.debug("Email to: " + recipient);
    log.debug("Email Subject is: " + subject);
    log.debug("Email Body is: " + body);
    email.setHostName(host);//  w w  w. j a  v  a  2s. c  o  m
    email.setSmtpPort(Integer.parseInt(port));
    email.setAuthenticator(new DefaultAuthenticator(username, password));
    // the method setSSL is deprecated on the newer versions of commons
    // email...
    email.setSSL("true".equalsIgnoreCase(ssl));
    email.setTLS("true".equalsIgnoreCase(tls));
    email.setFrom(from);
    email.setSubject(subject);
    email.setMsg(body);
    if (recipient.indexOf(",") >= 0) {
        String[] recs = recipient.split(",");
        for (String rec : recs) {
            email.addTo(rec);
        }
    } else {
        email.addTo(recipient);
    }
    email.send();
    return true;
}

From source file:com.t2tierp.controller.nfe.NfeCabecalhoController.java

public void enviaEmail() {
    try {/*w ww.ja  v  a2  s.c  o m*/
        if (getObjeto().getStatusNota().intValue() != 5) {
            throw new Exception("NF-e no autorizada. Envio de email no permitido!");
        }

        NfeConfiguracao configuracao = nfeConfiguracaoDao.getBean(NfeConfiguracao.class,
                new ArrayList<Filtro>());

        if (configuracao == null) {
            throw new Exception("Configurao NFe no definida");
        }
        if (configuracao.getEmailAssunto() == null || configuracao.getEmailSenha() == null
                || configuracao.getEmailServidorSmtp() == null || configuracao.getEmailTexto() == null
                || configuracao.getEmailUsuario() == null) {
            throw new Exception("Configurao de envio de email no definida");
        }

        MultiPartEmail email = new MultiPartEmail();
        email.setHostName(configuracao.getEmailServidorSmtp());
        email.setFrom(configuracao.getEmpresa().getEmail());
        email.addTo(getObjeto().getDestinatario().getEmail());
        email.setSubject(configuracao.getEmailAssunto());
        email.setMsg(configuracao.getEmailTexto());

        email.setAuthentication(configuracao.getEmailUsuario(), configuracao.getEmailSenha());
        if (configuracao.getEmailPorta() != null) {
            if (configuracao.getEmailAutenticaSsl() != null
                    && configuracao.getEmailAutenticaSsl().equals("S")) {
                email.setSSLOnConnect(true);
                email.setSslSmtpPort(configuracao.getEmailPorta().toString());
            } else {
                email.setSmtpPort(configuracao.getEmailPorta());
            }
        }

        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();

        EmailAttachment anexo = new EmailAttachment();
        anexo.setPath(context.getRealPath(diretorioXml) + System.getProperty("file.separator")
                + getObjeto().getChaveAcesso() + getObjeto().getDigitoChaveAcesso() + "-nfeproc.xml");
        anexo.setDisposition(EmailAttachment.ATTACHMENT);
        anexo.setDescription("Nota Fiscal Eletronica");
        anexo.setName(getObjeto().getChaveAcesso() + getObjeto().getDigitoChaveAcesso() + "-nfeproc.xml");

        EmailAttachment anexo2 = new EmailAttachment();
        anexo2.setPath(context.getRealPath(diretorioXml) + System.getProperty("file.separator")
                + getObjeto().getChaveAcesso() + getObjeto().getDigitoChaveAcesso() + ".pdf");
        anexo2.setDisposition(EmailAttachment.ATTACHMENT);
        anexo2.setDescription("Nota Fiscal Eletronica");
        anexo2.setName(getObjeto().getChaveAcesso() + getObjeto().getDigitoChaveAcesso() + ".pdf");

        email.attach(anexo);
        email.attach(anexo2);

        email.send();

        FacesContextUtil.adiconaMensagem(FacesMessage.SEVERITY_INFO, "Email enviado com sucesso", "");
    } catch (Exception ex) {
        ex.printStackTrace();
        FacesContextUtil.adiconaMensagem(FacesMessage.SEVERITY_ERROR, "Ocorreu um erro ao enviar o email.",
                ex.getMessage());
    }
}

From source file:dk.cubing.liveresults.action.admin.ScoresheetAction.java

/**
 * @return/*  w w w.ja v  a 2  s.  c  o  m*/
 */
public String exportResults() {
    if (competitionId != null) {
        Competition competitionTemplate = getCompetitionService().find(competitionId);
        if (competitionTemplate == null) {
            log.error("Could not load competition: {}", competitionId);
            return Action.ERROR;
        }
        setCompetition(competitionTemplate);

        try {
            // load WCA template from file
            InputStream is = ServletActionContext.getServletContext()
                    .getResourceAsStream(getSpreadSheetFilename());
            Workbook workBook;
            workBook = WorkbookFactory.create(is);
            is.close();

            // build special registration sheet
            generateRegistrationSheet(workBook, getCompetition());

            // build result sheets
            generateResultSheets(workBook, getCompetition());

            // set default selected sheet
            workBook.setActiveSheet(workBook.getSheetIndex(SHEET_TYPE_REGISTRATION));

            // email or just output to pdf?
            if (isSubmitResultsToWCA()) {
                // write workbook to temp file
                File temp = File.createTempFile(getCompetitionId(), ".xls");
                temp.deleteOnExit();
                OutputStream os = new FileOutputStream(temp);
                workBook.write(os);
                os.close();

                // Create the attachment
                EmailAttachment attachment = new EmailAttachment();
                attachment.setPath(temp.getPath());
                attachment.setDisposition(EmailAttachment.ATTACHMENT);
                attachment.setName(getCompetitionId() + ".xls");

                // send email
                MultiPartEmail email = new MultiPartEmail();
                email.setCharset(Email.ISO_8859_1);
                email.setHostName(getText("email.smtp.server"));
                if (!getText("email.username").isEmpty() && !getText("email.password").isEmpty()) {
                    email.setAuthentication(getText("email.username"), getText("email.password"));
                }
                email.setSSL("true".equals(getText("email.ssl")));
                email.setSubject("Results from " + getCompetition().getName());
                email.setMsg(getText("admin.export.message",
                        new String[] { getCompetition().getName(), getCompetition().getOrganiser() }));
                email.setFrom(getCompetition().getOrganiserEmail(), getCompetition().getOrganiser());
                email.addTo(getText("admin.export.resultsteamEmail"), getText("admin.export.resultsteam"));
                email.addCc(getCompetition().getOrganiserEmail(), getCompetition().getOrganiser());
                email.addCc(getCompetition().getWcaDelegateEmail(), getCompetition().getWcaDelegate());
                email.attach(attachment);
                email.send();

                return Action.SUCCESS;
            } else {
                // output generated spreadsheet
                log.debug("Ouputting generated workbook");
                out = new ByteArrayOutputStream();
                workBook.write(out);
                out.close();

                return "spreadsheet";
            }
        } catch (InvalidFormatException e) {
            log.error("Spreadsheet template are using an unsupported format.", e);
        } catch (IOException e) {
            log.error("Error reading spreadsheet template.", e);
        } catch (EmailException e) {
            log.error(e.getMessage(), e);
        }
        return Action.ERROR;
    } else {
        return Action.INPUT;
    }
}

From source file:ninja.postoffice.commonsmail.CommonsmailHelperImpl.java

/**
 * Creates a MultiPartEmail. Selects the correct implementation
 * regarding html (MultiPartEmail) and/or txt content or both.
 * /*from  w  w w.j  a v a 2  s. c o  m*/
 * Populates the mutlipart email accordingly with the txt / html content.
 */
@Override
public MultiPartEmail createMultiPartEmailWithContent(Mail mail) throws EmailException {

    MultiPartEmail multiPartEmail;

    // set if it is a txt or html mail:

    if (mail.getBodyHtml() == null || mail.getBodyHtml().equals("")) {

        multiPartEmail = new MultiPartEmail();
        multiPartEmail.setMsg(mail.getBodyText());

    } else if (mail.getBodyText() == null || mail.getBodyText().equals("")) {
        multiPartEmail = new HtmlEmail().setHtmlMsg(mail.getBodyHtml());
    } else {
        multiPartEmail = new HtmlEmail().setHtmlMsg(mail.getBodyHtml()).setTextMsg(mail.getBodyText());
    }

    // and return the nicely configured mail:
    return multiPartEmail;
}