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

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

Introduction

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

Prototype

public MultiPartEmail attach(final DataSource ds, final String name, final String description)
        throws EmailException 

Source Link

Document

Attach a file specified as a DataSource interface.

Usage

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  a  v  a  2  s  .co m*/
    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:eu.ggnet.dwoss.redtape.DocumentSupporterOperation.java

/**
 * This method send document to the e-Mail address that is in the customer set.
 * <p/>//from www  . j  a  v a2s. c  o m
 * @param document This is the Document that will be send.
 * @throws UserInfoException if the sending of the Mail is not successful.
 * @throws RuntimeException  if problems exist in the JasperExporter
 */
@Override
public void mail(Document document, DocumentViewType jtype) throws UserInfoException, RuntimeException {
    UiCustomer customer = customerService.asUiCustomer(document.getDossier().getCustomerId());

    String customerMailAddress = customerService.asCustomerMetaData(document.getDossier().getCustomerId())
            .getEmail();
    if (customerMailAddress == null) {
        throw new UserInfoException(
                "Kunde hat keine E-Mail Hinterlegt! Senden einer E-Mail ist nicht Mglich!");
    }

    String doctype = (jtype == DocumentViewType.DEFAULT ? document.getType().getName() : jtype.getName());

    try (InputStream is = mandator.getMailTemplateLocation().toURL().openStream();
            InputStreamReader templateReader = new InputStreamReader(is)) {
        String text = new MailDocumentParameter(customer.toTitleNameLine(), doctype)
                .eval(IOUtils.toString(templateReader));
        MultiPartEmail email = mandator.prepareDirectMail();

        email.setCharset("UTF-8");

        email.addTo(customerMailAddress);
        email.setSubject(document.getType().getName() + " | " + document.getDossier().getIdentifier());
        email.setMsg(text + mandator.getDefaultMailSignature());
        email.attach(new ByteArrayDataSource(JasperExportManager.exportReportToPdf(jasper(document, jtype)),
                "application/pdf"), "Dokument.pdf", "Das ist das Dokument zu Ihrem Aufrag als PDF.");
        for (MandatorMailAttachment mma : mandator.getDefaultMailAttachment()) {
            email.attach(mma.getAttachmentData().toURL(), mma.getAttachmentName(),
                    mma.getAttachmentDescription());
        }
        email.send();
    } catch (EmailException ex) {
        L.error("Error on Mail sending", ex);
        throw new UserInfoException("Das senden der Mail war nicht erfolgreich!\n" + ex.getMessage());
    } catch (IOException | JRException e) {
        throw new RuntimeException(e);
    }
}

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   ww  w .j  a v  a 2 s  . c  om
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:eu.ggnet.dwoss.misc.op.listings.SalesListingProducerOperation.java

/**
 * Prepare and send filejackets to the specified email address.
 * <p>//from   w  w w. j  ava  2s. co m
 * @param fileJackets files to be send
 */
private void prepareAndSend(List<FileJacket> fileJackets) {
    SubMonitor m = monitorFactory.newSubMonitor("Transfer");
    m.message("sending Mail");
    m.start();

    try {
        ListingMailConfiguration config = listingService.get().listingMailConfiguration();

        MultiPartEmail email = mandator.prepareDirectMail();
        email.setFrom(config.getFromAddress());
        email.addTo(config.getToAddress());
        email.setSubject(config.getSubject());
        email.setMsg(config.toMessage());

        for (FileJacket fj : fileJackets) {
            email.attach(new javax.mail.util.ByteArrayDataSource(fj.getContent(), "application/xls"),
                    fj.getHead() + fj.getSuffix(), "Die Hndlerliste fr die Marke ");
        }

        email.send();
        m.finish();
    } catch (EmailException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.softwareforge.pgpsigner.commands.MailCommand.java

@Override
public void executeInteractiveCommand(final String[] args) {

    SecretKey secretKey = getContext().getSignKey();

    String senderMail = secretKey.getMailAddress();
    String senderName = secretKey.getName();

    if (StringUtils.isEmpty(senderMail)) {
        System.out.println("Could not extract sender mail from sign key.");
        return;/* w  ww .  ja  v a  2  s  .  co m*/
    }

    for (final PublicKey key : getContext().getPartyRing().getVisibleKeys().values()) {

        if (key.isSigned() && !key.isMailed()) {

            try {
                String recipient = getContext().isSimulation() ? senderMail : key.getMailAddress();

                if (StringUtils.isEmpty(recipient)) {
                    System.out.println("No mail address for key " + key.getKeyId() + ", skipping.");
                    continue;
                }

                System.out.println("Sending Key " + key.getKeyId() + " to " + recipient);

                MultiPartEmail mail = new MultiPartEmail();
                mail.setHostName(getContext().getMailServerHost());
                mail.setSmtpPort(getContext().getMailServerPort());
                mail.setFrom(senderMail, senderName);
                mail.addTo(recipient);

                if (!getContext().isSimulation()) {
                    mail.addBcc(senderMail);
                }

                mail.setSubject("Your signed PGP key - " + key.getKeyId());
                mail.setMsg("This is your signed PGP key " + key.getKeyId() + " from the "
                        + getContext().getSignEvent() + " key signing event.");

                final String name = key.getKeyId() + ".asc";

                mail.attach(new DataSource() {

                    public String getContentType() {
                        return "application/pgp-keys";
                    }

                    public InputStream getInputStream() throws IOException {
                        return new ByteArrayInputStream(key.getArmor());
                    }

                    public String getName() {
                        return name;
                    }

                    public OutputStream getOutputStream() throws IOException {
                        throw new UnsupportedOperationException();
                    }
                }, name, "Signed Key " + key.getKeyId());

                mail.send();
                key.setMailed(true);

            } catch (EmailException ee) {
                System.out.println("Could not send mail for Key " + key.getKeyId());
            }
        }
    }
}

From source file:com.dominion.salud.pedicom.negocio.tools.MAILService.java

/**
 * configura el ciente de correo y envia el correo con un adjunto
 *
 * @param to// ww  w . j av  a2 s .c o m
 * @param attach el archivo que se adjunta en el correo
 * @param centro nombre del centro desde el que se envia
 * @throws Exception
 */
public void sendByMail(String to, Object attach, String centro) throws Exception {
    logger.debug("          Iniciando la configuracion del mail con sus parametros correspondientes ,"
            + " obtenemos los parametros de environment");

    String dataBase = routingDataSource.dbActual();
    allDataSources.getDatasources();

    Datasources dat = null;
    for (Datasources datas : allDataSources.getDatasources()) {
        if (datas.getNombreDatasource().equals(dataBase)) {
            dat = datas;
            break;
        }
    }
    if (StringUtils.isBlank(StringUtils.trim(dat.getHost()))) {
        throw new Exception(
                "El host es [" + StringUtils.trim(dat.getHost()) + "] , error de host desconocido o erroneo");
    }
    logger.debug("          El host es [" + StringUtils.trim(dat.getHost()) + "]");

    if (StringUtils.isBlank(StringUtils.trim(dat.getUsernameEmail()))) {
        throw new Exception("El usuario es [" + StringUtils.trim(dat.getUsernameEmail())
                + "], error de login en el correo , usuario desconocido o erroneo");
    }
    logger.debug("          El usuario es [" + StringUtils.trim(dat.getUsernameEmail()) + "]");

    if (StringUtils.isBlank(StringUtils.trim(dat.getPasswordEmail()))) {
        throw new Exception("La contrasea es [" + StringUtils.trim(dat.getPasswordEmail())
                + "], error de login en el correo , contrasea desconocida o erronea");
    }
    logger.debug("          La contrasea es [" + StringUtils.trim(dat.getPasswordEmail()) + "]");

    if (StringUtils.isBlank(to)) {
        throw new Exception("El destinatario es [" + to + "], no se especificaron destinatarios.");
    }
    logger.debug("          El destinatario es [" + to + "]");

    /*if (dat.getPort()== null) {
    throw new Exception("El puerto es [" + StringUtils.trim(environment.getProperty("mail.port")) + "], el puerto del servidor de correo falla");
    }*/
    logger.debug("          El puerto es [" + dat.getPort() + "]");

    /*if (StringUtils.isBlank(StringUtils.trim(environment.getProperty("mail.TLS")))) {
    throw new Exception("El TLS es [" + StringUtils.trim(environment.getProperty("mail.TLS")) + "]");
    }*/
    logger.debug("          El TLS es [" + dat.getTLS() + "]");

    System.setProperty("mail.imap.auth.plain.disable", "true");

    MultiPartEmail email = new MultiPartEmail();
    email.setHostName(StringUtils.trim(dat.getHost()));
    email.setAuthenticator(new DefaultAuthenticator(StringUtils.trim(dat.getUsernameEmail()),
            StringUtils.trim(dat.getPasswordEmail())));
    email.setFrom(StringUtils.trim(StringUtils.trim(dat.getUsernameEmail())), centro);
    email.setDebug(true);
    email.setSmtpPort(dat.getPort());
    email.setStartTLSEnabled(dat.getTLS());
    email.setSSLOnConnect(dat.getSSL());
    DataSource source = null;
    if (attach != null) {
        logger.debug("          Adjuntando pdf");
        source = new ByteArrayDataSource((InputStream) attach, "application/pdf");
        email.attach(source, "Pedido de centro " + centro + ".pdf", "Pedido de centro " + centro);
    }
    email.setSubject("Pedido de centro [" + centro + "]");
    logger.debug("          Realizando envio");
    email.addTo(to);
    email.send();

    try {
        if (!StringUtils.isBlank(StringUtils.trim(dat.getMailCC()))) {
            logger.debug("          Enviando a CC: " + dat.getMailCC());
            MultiPartEmail emailCC = new MultiPartEmail();
            emailCC.setHostName(StringUtils.trim(dat.getHost()));
            emailCC.setAuthenticator(new DefaultAuthenticator(StringUtils.trim(dat.getUsernameEmail()),
                    StringUtils.trim(dat.getPasswordEmail())));
            emailCC.setFrom(StringUtils.trim(StringUtils.trim(dat.getUsernameEmail())), centro);
            emailCC.setDebug(true);
            emailCC.setSmtpPort(dat.getPort());
            emailCC.setStartTLSEnabled(dat.getTLS());
            emailCC.setSSLOnConnect(dat.getSSL());
            if (attach != null) {
                logger.debug("          Adjuntando pdf a copia");
                emailCC.attach(source, "Pedido de centro " + centro + ".pdf", "Pedido de centro " + centro);
            }
            emailCC.setSubject("Pedido de centro " + centro);
            emailCC.addCc(StringUtils.split(StringUtils.trim(dat.getMailCC()), ","));
            emailCC.send();
        }
    } catch (Exception e) {
        logger.warn("          Se han producido errores al enviar los CC: " + e.toString());
    }
    logger.debug("     Finalizando envio email");

}

From source file:com.jk.mail.MailInfo.java

/**
 * Fill email.//from  w  w w.ja v  a 2 s  . co  m
 *
 * @param email
 *            the email
 * @throws EmailException
 *             the email exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void fillEmail(final MultiPartEmail email) throws EmailException, IOException {
    email.setHostName(getHost());
    email.setSmtpPort(getSmtpPort());

    email.addTo(getTo());
    email.setFrom(getFrom());
    email.setSubject(getSubject());
    email.setMsg(getMsg());
    email.setSSLOnConnect(isSecured());
    if (isRequiresAuthentication()) {
        email.setAuthentication(getUsername(), getPassword());
    }
    for (int i = 0; i < this.attachements.size(); i++) {
        final Attachment attachment = this.attachements.get(i);
        final ByteArrayDataSource ds = new ByteArrayDataSource(attachment.getData(), attachment.getMimeType());
        email.attach(ds, attachment.getName(), attachment.getDescription());
    }
}

From source file:info.toegepaste.controller.PdfController.java

public void CreatePdf(long studentId) {
    //Fonts/*from www .j a va  2s  . c  om*/
    Font header = new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD);
    Font normal = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL);

    //Declaration
    Student student = new Student();
    List<Course> courses;
    List<Exam> exams = null;
    Score score;
    int totaal = 0; //totaal van een vak berekenen
    int maxScore = 0; //max soore van een test
    int aantalVakken = 0; //aantal vakken waaraan student heeft deelgenomen
    int klasgemiddelde = 0; //hulpvariabele om klasgemiddelde op te vragen
    Double totaalGemiddelde = 0.0; //eindpercentage
    Double vermenigvuldigfactor = 0.0; //om score op 20 weer te geven
    ArrayList<Integer> gemiddeldes = new ArrayList<Integer>(); //gemiddeldes per vak
    ArrayList<Integer> gemiddeldesKlas = new ArrayList<Integer>(); //gemiddelde klas per vak

    PdfPCell cell;

    //Document
    Document document = new Document();

    //student opvullen
    student = pdfService.getStudent(studentId);

    //Tempfix
    //student.getClassgroup();

    //cursussen opvullen
    courses = courseService.getWithClassgroup(student.getClassgroup());

    for (int i = 0; i < courses.size(); i++) {
        //testen opvullen
        exams = pdfService.getExamsByCourse(courses.get(i));
        for (int j = 0; j < exams.size(); j++) {
            score = pdfService.getScoreByExamAndStudent(exams.get(j), student);
            //nagaan of de student heeft deelgenomen aan de test
            if (score != null) {
                // score op 20 weergeven
                vermenigvuldigfactor = 20 / (double) exams.get(j).getTotal();
                totaal += (int) (score.getScore() * vermenigvuldigfactor);
            }
            //klasgemiddelde voor een vak
            klasgemiddelde = pdfService.getAverageScoreByExam(exams.get(j));
            gemiddeldesKlas.add(klasgemiddelde);
        }
        if (exams.size() > 0) {
            gemiddeldes.add(totaal / exams.size());
            totaalGemiddelde += totaal / exams.size();
            aantalVakken++;
        }
        totaal = 0;
        exams.clear();
    }

    totaalGemiddelde = totaalGemiddelde / aantalVakken * 5;
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        PdfWriter.getInstance(document, outputStream);

        document.open();
        //header
        document.add(new Paragraph("Studenten Rapport", header));
        document.add(new Paragraph("Student:" + student.getFirstname() + " " + student.getLastname(), normal));
        document.add(new Paragraph("Klas:" + student.getClassgroup(), normal));
        document.add(new Paragraph("Alle scores worden op 20 weergegeven", normal));

        //table
        PdfPTable table = new PdfPTable(3);

        //create tableheaders
        PdfPCell c1 = new PdfPCell(new Phrase("Vak"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Score"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);

        c1 = new PdfPCell(new Phrase("Gemiddelde"));
        c1.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(c1);
        table.setHeaderRows(1);

        for (int i = 0; i < aantalVakken; i++) {
            cell = new PdfPCell(new Phrase(gemiddeldes.get(i).toString()));
            if (gemiddeldes.get(i) < 10) {
                cell.setBackgroundColor(BaseColor.RED);
            }

            table.addCell(courses.get(i).getName());
            table.addCell(cell);
            table.addCell(gemiddeldesKlas.get(i).toString());
        }

        document.add(table);

        //end
        document.add(new Paragraph("Totaal behaald percentage:" + totaalGemiddelde, normal));
        document.close();

    } catch (DocumentException e) {
        e.printStackTrace();
        //  } catch (FileNotFoundException e) {
        //   e.printStackTrace();
    }
    MultiPartEmail email = new MultiPartEmail();
    email.setHostName("smtp.googlemail.com");
    email.setSmtpPort(587);
    email.setSSLOnConnect(true);
    email.setAuthenticator(new DefaultAuthenticator("bitmescoretracker@gmail.com", "bitmeScore"));
    try {

        email.addTo(student.getEmail());
        email.setFrom("bitmescoretracker@gmail.com");
        email.setSubject("Requested scores , scoretracker");
        email.setMsg("Here are the scores you requested!");

        //  EmailAttachment attachment = new EmailAttachment();
        //attachment.setDescription("PDF met uw punten");
        // attachment.setName(student.getFirstname() + " " + student.getLastname() + " scores");
        byte[] bytes = outputStream.toByteArray();

        DataSource source = new javax.mail.util.ByteArrayDataSource(bytes, "application/pdf");
        System.out.println("Stuff");

        /* try{
         source = outputStream.write(bytes);
         }catch(IOException e){
             e.printStackTrace();
         }*/
        email.attach(source, student.getFirstname() + " " + student.getLastname() + " scores", "stuff");

        email.send();
    } catch (EmailException ex) {
        ex.printStackTrace();
    }

}

From source file:annis.gui.ReportBugWindow.java

private boolean sendBugReport(String bugEMailAddress, byte[] screenImage, String imageMimeType) {
    MultiPartEmail mail = new MultiPartEmail();
    try {//from w ww  . j  a  v a2 s .c  o  m
        // server setup
        mail.setHostName("localhost");

        // content of the mail
        mail.addReplyTo(form.getField("email").getValue().toString(),
                form.getField("name").getValue().toString());
        mail.setFrom(bugEMailAddress);
        mail.addTo(bugEMailAddress);

        mail.setSubject("[ANNIS BUG] " + form.getField("summary").getValue().toString());

        // TODO: add info about version etc.
        StringBuilder sbMsg = new StringBuilder();

        sbMsg.append("Reporter: ").append(form.getField("name").getValue().toString()).append(" (")
                .append(form.getField("email").getValue().toString()).append(")\n");
        sbMsg.append("Version: ").append(VaadinSession.getCurrent().getAttribute("annis-version")).append("\n");
        sbMsg.append("URL: ").append(UI.getCurrent().getPage().getLocation().toASCIIString()).append("\n");

        sbMsg.append("\n");

        sbMsg.append(form.getField("description").getValue().toString());
        mail.setMsg(sbMsg.toString());

        if (screenImage != null) {
            try {
                mail.attach(new ByteArrayDataSource(screenImage, imageMimeType), "screendump.png",
                        "Screenshot of the browser content at time of bug report");
            } catch (IOException ex) {
                log.error(null, ex);
            }

            File logfile = new File(VaadinService.getCurrent().getBaseDirectory(),
                    "/WEB-INF/log/annis-gui.log");
            if (logfile.exists() && logfile.isFile() && logfile.canRead()) {
                mail.attach(new FileDataSource(logfile), "annis-gui.log",
                        "Logfile of the GUI (shared by all users)");
            }
        }

        mail.send();
        return true;

    } catch (EmailException ex) {
        Notification.show("E-Mail not configured on server",
                "If this is no Kickstarter version please ask the adminstrator of this ANNIS-instance for assistance. "
                        + "Bug reports are not available for ANNIS Kickstarter",
                Notification.Type.ERROR_MESSAGE);
        log.error(null, ex);
        return false;
    }
}

From source file:com.itcs.commons.email.impl.RunnableSendHTMLEmail.java

private void addAttachments(MultiPartEmail email, List<EmailAttachment> attachments) throws EmailException {

    if (attachments != null && attachments.size() > 0) {
        String maxStringValue = getSession().getProperty(MAX_ATTACHMENTS_SIZE_PROP_NAME);
        //            System.out.println("maxStringValue= " + maxStringValue);
        long maxAttachmentSize = DISABLE_MAX_ATTACHMENTS_SIZE;
        try {/*from   w w w.ja v a2 s  .co m*/
            maxAttachmentSize = Long.parseLong(maxStringValue);
        } catch (NumberFormatException e) {
            Logger.getLogger(RunnableSendHTMLEmail.class.getName()).log(Level.WARNING,
                    "DISABLE_MAX_ATTACHMENTS_SIZE MailSession does not have property "
                            + MAX_ATTACHMENTS_SIZE_PROP_NAME);
        }

        long size = 0;
        for (EmailAttachment attach : attachments) {
            if (maxAttachmentSize != EmailClient.DISABLE_MAX_ATTACHMENTS_SIZE) {
                size += attach.getSize();
                if (size > maxAttachmentSize) {
                    throw new EmailException(
                            "Adjuntos exceden el tamao maximo permitido (" + maxAttachmentSize + "),"
                                    + " pruebe enviando menos archivos adjuntos, o de menor tamao.");
                }
            }
            if (attach.getData() != null) {
                try {
                    email.attach(new ByteArrayDataSource(attach.getData(), attach.getMimeType()),
                            attach.getName(), attach.getMimeType());
                } catch (IOException e) {
                    throw new EmailException("IOException Attachment has errors," + e.getMessage());
                } catch (EmailException e) {
                    throw new EmailException("EmailException Attachment has errors," + e.getMessage());
                }
            } else {
                email.attach(attach);
            }
        }

    }

}