日期:2014-05-17 浏览次数:21006 次
public void process() { Connection conn = null; try { //报表内嵌了SQL,只要传入参数,数据库连接即可。 conn = dataSource.getConnection(); Map parameters = new HashMap(); parameters.put("startTime", "20110101"); parameters.put("endTime", "20111001"); String jasperFile = "d://*****/" + "*****.jasper"; File reportFile = new File(jasperFile); if (!reportFile.exists()) throw new JRRuntimeException("File jasper not found. The report design must be compiled first."); JasperPrint jasperPrint = JasperFillManager.fillReport( jasperFile, parameters, conn ); JRHtmlExporter exporter = new JRHtmlExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); ByteArrayOutputStream htmlOutputData = new ByteArrayOutputStream(); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, htmlOutputData); exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl); exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imagePath); exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, true); exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, false); exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8"); Map imageNameMap = new HashMap(); exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imageNameMap); exporter.exportReport(); //attach the html data from htmlOutputData byte[] imageData = null; for (Iterator it = imageNameMap.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); String imageName = (String) entry.getKey(); imageData = (byte[]) entry.getValue(); //attach imageData using imageName as Content-ID } sendEmail(htmlOutputData.toByteArray(), imageData, imageNameMap); } catch (Exception e) { e.printStackTrace(); } finally { try { if (conn != null) conn.close(); } catch (Exception e) { } } }
public void sendEmail(final byte[] attachmentData, final byte[] imageData, final Map<String, byte[]> imageNameMap) throws MessagingException { String host = "smtp.126.com"; final String account = "****@126.com"; final String toAddress = "****@163.com"; String username = ""****@126.com"; String password = "******"; JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost(host); sender.setUsername(username); sender.setPassword(password); MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { Multipart multipart = new MimeMultipart(); MimeBodyPart htmlAttachment = new MimeBodyPart(); String html = new String(attachmentData, "utf-8"); for (String imageName : imageNameMap.keySet()) { html = html.replace("/html/image.jsp?image=" + imageName, "cid:" + imageName); } htmlAttachment.setContent(html, "text/html;charset=\"utf-8\""); // multipart.addBodyPart(htmlAttachment); //当你有多个报表图片时 for (