Email Attachments using Java Mail


        String html = "Your report data is attached for: " + report.getTitle() + " - " + new Date();
        String plain = html;
        List attachments = new ArrayList();
        List data = getReportData(report);
        
        if(report.isLineChart()) {
            byte[] image = getLineChart(data, report); //RestUtil.downloadImage(url);
            if(image != null) {
                MimeBodyPart attachment = new MimeBodyPart();
                DataSource ds = new ByteArrayDataSource(image, "application/x-any");
                attachment.setDataHandler(new DataHandler(ds));
                attachment.setDescription("LineChart");
                attachment.setFileName(report.getTitle() + ".png");
                attachments.add(attachment);
            }
        }
        
        String csv = ExcelUtil.getCSVFromData(data, report);   
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setText(csv);
        mbp.setDescription("Report CSV");
        mbp.setFileName(report.getTitle() + ".csv");
        attachments.add(mbp);
        
        // Get and attach xls
        byte[] excel = ExcelUtil.convertCSVToExcell(csv);
        MimeBodyPart excelPart = new MimeBodyPart();
        DataSource ds = new ByteArrayDataSource(excel, "application/x-any");
        excelPart.setDataHandler(new DataHandler(ds));
        excelPart.setDescription("Report Excel");
        excelPart.setFileName(report.getTitle() + ".xls");
        attachments.add(excelPart);

        String subject = "Report: " + report.getTitle();
        EmailSettings settings = emailService.getEmailSettingsByKey(Key.REGULAR_EMAIL_SETTINGS);
        EmailUtil.sendScheduledReport(subject, html, plain, attachments, emails, settings, schedule);


public static void sendScheduledReport(String subject, String html, String plain, List attachments, List emails, EmailSettings settings, ReportSchedule schedule) {

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", tls);
        props.put("mail.smtp.host", settings.getServerAddress());
        props.put("mail.smtp.port", settings.getServerPort());
        props.put("mail.smtp.auth", "false");

        try {
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(false);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(schedule.getFromEmail(), schedule.getFromName()));
            
            for(String address : emails) {
                message.addRecipient(Message.RecipientType.BCC, new InternetAddress(address));
            }

            message.setSubject(subject);
            setMessageParts(message, plain, html, attachments);
            message.setSentDate(new Date());
            
            Transport transport = session.getTransport("smtp");
            transport.connect();
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();

        } catch(Exception ex) {
            ErrorHandler.handle(ex, logger, null);
        }
    }

public static void setMessageParts(MimeMessage message, String text, String html, List attachments) throws MessagingException {
        MimeMultipart rootMixedMultipart = new MimeMultipart("mixed");
        message.setContent(rootMixedMultipart);

        MimeMultipart nestedRelatedMultipart = new MimeMultipart("related");
        MimeBodyPart relatedBodyPart = new MimeBodyPart();
        relatedBodyPart.setContent(nestedRelatedMultipart);
        rootMixedMultipart.addBodyPart(relatedBodyPart);

        MimeMultipart messageBody = new MimeMultipart("alternative");
        MimeBodyPart bodyPart = null;
        for (int i = 0; i < nestedRelatedMultipart.getCount(); i++) {
            BodyPart bp = nestedRelatedMultipart.getBodyPart(i);
            if (bp.getFileName() == null) {
                bodyPart = (MimeBodyPart) bp;
            }
        }
        if (bodyPart == null) {
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            nestedRelatedMultipart.addBodyPart(mimeBodyPart);
            bodyPart = mimeBodyPart;
        }
        bodyPart.setContent(messageBody, "text/alternative");

        // Create the plain text part of the message.
        if(text != null) {
            MimeBodyPart plainTextPart = new MimeBodyPart();
            plainTextPart.setText(text, "UTF-8");
            messageBody.addBodyPart(plainTextPart);
        }

        // Create the HTML text part of the message.
        if(html != null) {
            MimeBodyPart htmlTextPart = new MimeBodyPart();
            //htmlTextPart.setText(html, "text/html; charset=UTF-8");
            htmlTextPart.setText("\n" + html, "UTF-8", "html");
            messageBody.addBodyPart(htmlTextPart);
        }
        
        // Attach multi-part-mime-body-parts-and-stuff
        if(attachments != null && !attachments.isEmpty()) {
            for(MimeBodyPart part : attachments) {
                rootMixedMultipart.addBodyPart(part);
            }
        }
        
    }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s