List of usage examples for javax.mail.internet MimeBodyPart setHeader
@Override public void setHeader(String name, String value) throws MessagingException
From source file:com.adaptris.mail.MailSenderImp.java
private void addAttachmentsToMessage(MimeMultipart multipart) throws MailException { try {// w ww . j a v a 2 s. co m for (Attachment a : attachments) { MimeBodyPart part = create(a.getBytes(), new InternetHeaders(), a.getEncoding()); part.setHeader(Mail.CONTENT_TYPE, a.getContentType()); ContentDisposition cd = new ContentDisposition(); cd.setDisposition(Mail.DISPOSITION_TYPE_ATTACHMENT); if (a.getFilename() != null) { cd.setParameter(Mail.DISPOSITION_PARAM_FILENAME, a.getFilename()); } part.setDisposition(cd.toString()); multipart.addBodyPart(part); } } catch (Exception e) { throw new MailException(e); } }
From source file:com.threewks.thundr.gmail.GmailMailer.java
private MimeMessage createMime(String bodyText, String subject, Map<String, String> to, List<Attachment> pdfs) throws MessagingException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); Set<InternetAddress> toAddresses = getInternetAddresses(to); if (!toAddresses.isEmpty()) { email.addRecipients(javax.mail.Message.RecipientType.TO, toAddresses.toArray(new InternetAddress[to.size()])); }/*from ww w . j ava 2s . com*/ email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/html"); mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); for (Attachment attachmentPdf : pdfs) { MimeBodyPart attachment = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(attachmentPdf.getData(), "application/pdf"); attachment.setDataHandler(new DataHandler(source)); attachment.setFileName(attachmentPdf.getFileName()); multipart.addBodyPart(mimeBodyPart); multipart.addBodyPart(attachment); } email.setContent(multipart); return email; }
From source file:com.adaptris.util.text.mime.MultiPartOutput.java
/** * Add a new part to the mime multipart. * //ww w . j a v a 2 s. co m * @param part an already existing mimebody part * @param contentId the id to set the content with. * @throws MessagingException on error manipulating the bodypart * @throws IOException on general IO error. */ public void addPart(MimeBodyPart part, String contentId) throws MessagingException, IOException { part.setHeader(HEADER_CONTENT_ID, contentId); parts.add(new KeyedBodyPart(contentId, part)); }
From source file:com.threewks.thundr.gmail.GmailMailer.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email. * @param bodyText Body text of the email. * @return MimeMessage to be used to send email. * @throws MessagingException/* w w w. j a v a2 s. co m*/ */ protected MimeMessage createEmailWithAttachment(Set<InternetAddress> to, InternetAddress from, Set<InternetAddress> cc, Set<InternetAddress> bcc, InternetAddress replyTo, String subject, String bodyText, List<com.threewks.thundr.mail.Attachment> attachments) { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); try { email.setFrom(from); if (to != null) { email.addRecipients(javax.mail.Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()])); } if (cc != null) { email.addRecipients(javax.mail.Message.RecipientType.CC, cc.toArray(new InternetAddress[cc.size()])); } if (bcc != null) { email.addRecipients(javax.mail.Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()])); } if (replyTo != null) { email.setReplyTo(new Address[] { replyTo }); } email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/html"); mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); if (attachments != null) { for (com.threewks.thundr.mail.Attachment attachment : attachments) { mimeBodyPart = new MimeBodyPart(); BasicViewRenderer renderer = new BasicViewRenderer(viewResolverRegistry); renderer.render(attachment.view()); byte[] data = renderer.getOutputAsBytes(); String attachmentContentType = renderer.getContentType(); String attachmentCharacterEncoding = renderer.getCharacterEncoding(); populateMimeBodyPart(mimeBodyPart, attachment, data, attachmentContentType, attachmentCharacterEncoding); multipart.addBodyPart(mimeBodyPart); } } email.setContent(multipart); } catch (MessagingException e) { Logger.error(e.getMessage()); Logger.error( "Failed to create email from: %s;%s, to: %s, cc: %s, bcc: %s, replyTo %s;%s, subject %s, body %s, number of attachments %d", from.getAddress(), from.getPersonal(), Transformers.InternetAddressesToString.from(to), Transformers.InternetAddressesToString.from(cc), Transformers.InternetAddressesToString.from(bcc), replyTo == null ? "null" : replyTo.getAddress(), replyTo == null ? "null" : replyTo.getPersonal(), subject, bodyText, attachments == null ? 0 : attachments.size()); throw new GmailException(e); } return email; }
From source file:com.zotoh.crypto.CryptoUte.java
/** * @param cType//from w w w . java2s . c om * @param cte * @param contentLoc * @param cid * @param msg * @return * @throws MessagingException * @throws IOException * @throws GeneralSecurityException */ public static MimeBodyPart compressContent(String cType, String cte, String contentLoc, String cid, StreamData msg) throws MessagingException, IOException, GeneralSecurityException { tstEStrArg("content-type", cType); tstEStrArg("content-id", cid); tstObjArg("input-content", msg); SMIMECompressedGenerator gen = new SMIMECompressedGenerator(); MimeBodyPart bp = new MimeBodyPart(); SmDataSource ds; if (msg.isDiskFile()) { ds = new SmDataSource(msg.getFileRef(), cType); } else { ds = new SmDataSource(msg.getBytes(), cType); } if (!isEmpty(contentLoc)) { bp.setHeader("content-location", contentLoc); } try { bp.setHeader("content-id", cid); bp.setDataHandler(new DataHandler(ds)); bp = gen.generate(bp, SMIMECompressedGenerator.ZLIB); } catch (SMIMEException e) { throw new GeneralSecurityException(e); } if (true) { int pos = cid.lastIndexOf(">"); if (pos >= 0) { cid = cid.substring(0, pos) + "--z>"; } else { cid = cid + "--z"; } } if (!isEmpty(contentLoc)) { bp.setHeader("content-location", contentLoc); } bp.setHeader("content-id", cid); // always base64 cte = "base64"; if (!isEmpty(cte)) { bp.setHeader("content-transfer-encoding", cte); } return bp; }
From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java
/** * Creates MimeMessage with supplied values * //ww w. ja va2 s . c o m * @param to - to email address * @param docType - String value for the attached document type * @param subject - Subject for the email * @param instructions - email body * @param content - content to be sent as attachment * @return MimeMessage instance */ public MimeMessage createMessage(String to, String docType, String subject, String instructions, String content, String metadataXMl, String title, String indexBodyToken, String readmeToken) { final MimeMessage msg = mailSender.createMimeMessage(); UUID uniqueID = UUID.randomUUID(); tempZipFolder = new File(secEmailTempZipLocation + "/" + uniqueID); try { msg.setFrom(new InternetAddress(getFrom())); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // The readable part final MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(instructions); mbp1.setHeader("Content-Type", "text/plain"); // The notification final MimeBodyPart mbp2 = new MimeBodyPart(); final String contentType = "application/xml; charset=UTF-8"; String extension; // HL7 messages should be a txt file, otherwise xml if (StringUtils.contains(instructions, "HL7_V2_CLINICAL_NOTE")) { extension = TXT_EXT; } else { extension = XML_EXT; } final String fileName = docType + UUID.randomUUID() + extension; // final DataSource ds = new AttachmentDS(fileName, content, contentType); // mbp2.setDataHandler(new DataHandler(ds)); /******** START NHIN COMPLIANCE CHANGES *****/ boolean isTempZipFolderCreated = tempZipFolder.mkdirs(); if (!isTempZipFolderCreated) { LOG.error("Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath()); throw new ApplicationRuntimeException( "Error creating temp folder for NHIN zip file: " + tempZipFolder.getAbsolutePath()); } String indexFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/INDEX.HTM")); String readmeFileString = FileUtils.readFileToString(new File(secEmailTempZipLocation + "/README.TXT")); indexFileString = StringUtils.replace(indexFileString, "@document_title@", title); indexFileString = StringUtils.replace(indexFileString, "@indexBodyToken@", indexBodyToken); FileUtils.writeStringToFile(new File(tempZipFolder + "/INDEX.HTM"), indexFileString); readmeFileString = StringUtils.replace(readmeFileString, "@readmeToken@", readmeToken); FileUtils.writeStringToFile(new File(tempZipFolder + "/README.TXT"), readmeFileString); // move template files & replace tokens // FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/INDEX.HTM"), tempZipFolder, false); // FileUtils.copyFileToDirectory(new File(secEmailTempZipLocation + "/README.TXT"), tempZipFolder, false); // create sub-directories String nhinSubDirectoryPath = tempZipFolder + "/IHE_XDM/SUBSET01"; File nhinSubDirectory = new File(nhinSubDirectoryPath); boolean isNhinSubDirectoryCreated = nhinSubDirectory.mkdirs(); if (!isNhinSubDirectoryCreated) { LOG.error("Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath()); throw new ApplicationRuntimeException( "Error creating NHIN sub-directory: " + nhinSubDirectory.getAbsolutePath()); } FileOutputStream metadataStream = new FileOutputStream( new File(nhinSubDirectoryPath + "/METADATA.XML")); metadataStream.write(metadataXMl.getBytes()); metadataStream.flush(); metadataStream.close(); FileOutputStream documentStream = new FileOutputStream( new File(nhinSubDirectoryPath + "/DOCUMENT" + extension)); documentStream.write(content.getBytes()); documentStream.flush(); documentStream.close(); String zipFile = secEmailTempZipLocation + "/" + tempZipFolder.getName() + ".ZIP"; byte[] buffer = new byte[1024]; // FileOutputStream fos = new FileOutputStream(zipFile); // ZipOutputStream zos = new ZipOutputStream(fos); List<String> fileList = generateFileList(tempZipFolder); ByteArrayOutputStream bout = new ByteArrayOutputStream(fileList.size()); ZipOutputStream zos = new ZipOutputStream(bout); // LOG.info("File List size: "+fileList.size()); for (String file : fileList) { ZipEntry ze = new ZipEntry(file); zos.putNextEntry(ze); FileInputStream in = new FileInputStream(tempZipFolder + File.separator + file); int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); } in.close(); } zos.closeEntry(); // remember close it zos.close(); DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip"); mbp2.setDataHandler(new DataHandler(source)); mbp2.setFileName(docType + ".ZIP"); /******** END NHIN COMPLIANCE CHANGES *****/ // mbp2.setFileName(fileName); // mbp2.setHeader("Content-Type", contentType); final Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); msg.setSentDate(new Date()); // FileUtils.deleteDirectory(tempZipFolder); } catch (AddressException e) { LOG.error("Error creating email message!"); throw new ApplicationRuntimeException("Error creating message!", e); } catch (MessagingException e) { LOG.error("Error creating email message!"); throw new ApplicationRuntimeException("Error creating message!", e); } catch (IOException e) { LOG.error(e.getMessage()); throw new ApplicationRuntimeException(e.getMessage()); } finally { //reset filelist contents fileList = new ArrayList<String>(); } return msg; }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail./* w w w . ja v a2 s . c o m*/ * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:Implement.Service.AdminServiceImpl.java
@Override public boolean sendPackageApprovedEmail(PackageApprovedEmailData emailData) throws MessagingException { String path = System.getProperty("catalina.base"); MimeBodyPart logo = new MimeBodyPart(); // attach the file to the message DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/logoIcon.png")); logo.setDataHandler(new DataHandler(source)); logo.setFileName("logoIcon.png"); logo.setDisposition(MimeBodyPart.INLINE); logo.setHeader("Content-ID", "<logo_Icon>"); // cid:image_cid MimeBodyPart facebook = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/facebookIcon.png")); facebook.setDataHandler(new DataHandler(source)); facebook.setFileName("facebookIcon.png"); facebook.setDisposition(MimeBodyPart.INLINE); facebook.setHeader("Content-ID", "<fb_Icon>"); // cid:image_cid MimeBodyPart twitter = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/twitterIcon.png")); twitter.setDataHandler(new DataHandler(source)); twitter.setFileName("twitterIcon.png"); twitter.setDisposition(MimeBodyPart.INLINE); twitter.setHeader("Content-ID", "<twitter_Icon>"); // cid:image_cid MimeBodyPart insta = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/instaIcon.png")); insta.setDataHandler(new DataHandler(source)); insta.setFileName("instaIcon.png"); insta.setDisposition(MimeBodyPart.INLINE); insta.setHeader("Content-ID", "<insta_Icon>"); // cid:image_cid MimeBodyPart youtube = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/youtubeIcon.png")); youtube.setDataHandler(new DataHandler(source)); youtube.setFileName("youtubeIcon.png"); youtube.setDisposition(MimeBodyPart.INLINE); youtube.setHeader("Content-ID", "<yt_Icon>"); // cid:image_cid MimeBodyPart pinterest = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/pinterestIcon.png")); pinterest.setDataHandler(new DataHandler(source)); pinterest.setFileName("pinterestIcon.png"); pinterest.setDisposition(MimeBodyPart.INLINE); pinterest.setHeader("Content-ID", "<pin_Icon>"); // cid:image_cid String content = "<div style=' width: 507px;background-color: #f2f2f4;'>" + " <div style='padding: 30px 0;text-align: center; color: #fff; background-color: #ff514e;font-size: 30px;font-weight: bold;'>" + " <img style=' text-align:center;' width=57 height=57 src='cid:logo_Icon'/>" + " <p style='margin:25px 0px 0px 0px;'> Package Approved! </p>" + " </div>" + " <div style=' padding: 50px;margin-bottom: 20px;'>" + " <div id='email-form'>" + " <div style='margin-bottom: 20px'>" + " Hi " + emailData.getLastName() + " ,<br/>" + " Your package " + emailData.getLastestPackageName() + " has been approved" + " </div>" + " <div style='margin-bottom: 20px'>" + " Thanks,<br/>" + " Youtripper team\n" + " </div>" + " </div>" + " <div style='border-top: solid 1px #c4c5cc;text-align:center;'>" + " <p style='text-align: center; color: #3b3e53;margin-top: 10px;margin-bottom: 0px;font-size: 10px;'>Sent from Youtripper.com</p>" + " <div>" + " <a href='https://www.facebook.com/youtrippers/'><img style='margin:10px;' src='cid:fb_Icon' alt=''/></a>" + " <a href='https://twitter.com/youtrippers'><img style='margin:10px;' src='cid:twitter_Icon' alt=''/></a>" + " <a href='https://www.instagram.com/youtrippers/'><img style='margin:10px;' src='cid:insta_Icon' alt=''/></a>" + " <a href='https://www.youtube.com/channel/UCtd4xd_SSjRR9Egug7tXIWA'><img style='margin:10px;' src='cid:yt_Icon' alt=''/></a>" + " <a href='https://www.pinterest.com/youtrippers/'><img style='margin:10px;' src='cid:pin_Icon' alt=''/></a>" + " </div>" + " <p>Youtripper Ltd., 56 Soi Seri Villa, Srinakarin Rd., Nongbon," + " <br>Pravet, Bangkok, Thailand 10250</p>" + " </div>" + " </div>" + "</div>"; MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(content, "US-ASCII", "html"); Multipart mp = new MimeMultipart("related"); mp.addBodyPart(mbp1);// w w w . ja v a 2 s . c om mp.addBodyPart(logo); mp.addBodyPart(facebook); mp.addBodyPart(twitter); mp.addBodyPart(insta); mp.addBodyPart(youtube); mp.addBodyPart(pinterest); final String username = "noreply@youtripper.com"; final String password = "Tripper190515"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "mail.youtripper.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("noreply@youtripper.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailData.getEmail())); message.setSubject("Package Approved!"); message.setContent(mp); message.saveChanges(); Transport.send(message); return true; }
From source file:com.openkm.util.MailUtils.java
/** * Create a mail./*from w w w . j ava 2s . com*/ * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null && Config.SEND_MAIL_FROM_USER) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java
private MimeBodyPart constructEmail(int index, ApplicationGroup appGroup, StringBuilder body) throws IOException, MessagingException { if (index == 0 && !StringUtils.isEmpty(headerNote)) body.append(headerNote);/*from ww w . j a va 2 s.c om*/ numberFormatter.setMaximumFractionDigits(1); numberFormatter.setMinimumFractionDigits(1); File file = createImage(appGroup); if (file == null) return null; DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0); String link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks), end); body.append(String.format("<b><h4><a href='%s'>%s</a> Weekly Costs:</h4></b>", link, appGroup.getDisplayName())); body.append("<table style=\"border: 1px solid #DDD; border-collapse: collapse\">"); body.append( "<tr style=\"background-color: whiteSmoke;text-align:center\" ><td style=\"border-left: 1px solid #DDD;\"></td>"); for (int i = 0; i <= accounts.size(); i++) { int cols = i == accounts.size() ? 1 : regions.size(); String accName = i == accounts.size() ? "total" : accounts.get(i).name; body.append(String.format( "<td style=\"border-left: 1px solid #DDD;font-weight: bold;padding: 4px\" colspan='%d'>", cols)) .append(accName).append("</td>"); } body.append("</tr>"); body.append("<tr style=\"background-color: whiteSmoke;text-align:center\" ><td></td>"); for (int i = 0; i < accounts.size(); i++) { boolean first = true; for (Region region : regions) { body.append("<td style=\"font-weight: bold;padding: 4px;" + (first ? "border-left: 1px solid #DDD;" : "") + "\">").append(region.name) .append("</td>"); first = false; } } body.append("<td style=\"border-left: 1px solid #DDD;\"></td></tr>"); Map<String, Double> costs = Maps.newHashMap(); Interval interval = new Interval(end.minusWeeks(numWeeks), end); double[] total = new double[numWeeks]; for (Product product : products) { List<ResourceGroup> resourceGroups = getResourceGroups(appGroup, product); if (resourceGroups.size() == 0) { continue; } DataManager dataManager = config.managers.getCostManager(product, ConsolidateType.weekly); if (dataManager == null) { continue; } for (int i = 0; i < accounts.size(); i++) { List<Account> accountList = Lists.newArrayList(accounts.get(i)); TagLists tagLists = new TagLists(accountList, regions, null, Lists.newArrayList(product), null, null, resourceGroups); Map<Tag, double[]> data = dataManager.getData(interval, tagLists, TagType.Region, AggregateType.none, false); for (Tag tag : data.keySet()) { for (int week = 0; week < numWeeks; week++) { String key = accounts.get(i) + "|" + tag + "|" + week; if (costs.containsKey(key)) costs.put(key, data.get(tag)[week] + costs.get(key)); else costs.put(key, data.get(tag)[week]); total[week] += data.get(tag)[week]; } } } } boolean firstLine = true; DateTime currentWeekEnd = end; for (int week = numWeeks - 1; week >= 0; week--) { String weekStr; if (week == numWeeks - 1) weekStr = "Last week"; else weekStr = (numWeeks - week - 1) + " weeks ago"; String background = week % 2 == 1 ? "background: whiteSmoke;" : ""; body.append(String.format( "<tr style=\"%s\"><td nowrap style=\"border-left: 1px solid #DDD;padding: 4px\">%s (%s - %s)</td>", background, weekStr, formatter.print(currentWeekEnd.minusWeeks(1)).substring(5), formatter.print(currentWeekEnd).substring(5))); for (int i = 0; i < accounts.size(); i++) { Account account = accounts.get(i); for (int j = 0; j < regions.size(); j++) { Region region = regions.get(j); String key = account + "|" + region + "|" + week; double cost = costs.get(key) == null ? 0 : costs.get(key); Double lastCost = week == 0 ? null : costs.get(account + "|" + region + "|" + (week - 1)); link = getLink("column", ConsolidateType.daily, appGroup, Lists.newArrayList(account), Lists.newArrayList(region), currentWeekEnd.minusWeeks(1), currentWeekEnd); body.append(getValueCell(cost, lastCost, link, firstLine)); } } link = getLink("column", ConsolidateType.daily, appGroup, accounts, regions, currentWeekEnd.minusWeeks(1), currentWeekEnd); body.append(getValueCell(total[week], week == 0 ? null : total[week - 1], link, firstLine)); body.append("</tr>"); firstLine = false; currentWeekEnd = currentWeekEnd.minusWeeks(1); } body.append("</table>"); numberFormatter.setMaximumFractionDigits(0); numberFormatter.setMinimumFractionDigits(0); if (!StringUtils.isEmpty(throughputMetrics)) body.append(throughputMetrics); body.append("<br><img src=\"cid:image_cid_" + index + "\"><br>"); for (Map.Entry<String, List<String>> entry : appGroup.data.entrySet()) { String product = entry.getKey(); List<String> selected = entry.getValue(); if (selected == null || selected.size() == 0) continue; link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks), end); body.append(String.format("<b><h4>%s in <a href='%s'>%s</a>:</h4></b>", getResourceGroupsDisplayName(product), link, appGroup.getDisplayName())); for (String name : selected) body.append(" ").append(name).append("<br>"); } body.append("<hr><br>"); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setFileName(file.getName()); DataSource ds = new ByteArrayDataSource(new FileInputStream(file), "image/png"); mimeBodyPart.setDataHandler(new DataHandler(ds)); mimeBodyPart.setHeader("Content-ID", "<image_cid_" + index + ">"); mimeBodyPart.setHeader("Content-Disposition", "inline"); mimeBodyPart.setDisposition(MimeBodyPart.INLINE); file.delete(); return mimeBodyPart; }