List of usage examples for javax.mail.internet MimeMultipart addBodyPart
@Override public synchronized void addBodyPart(BodyPart part) throws MessagingException
From source file:lucee.runtime.net.mail.HtmlEmailImpl.java
/** * @throws EmailException EmailException * @throws MessagingException MessagingException */// w ww. ja v a 2s.c o m private void buildAttachments() throws MessagingException, EmailException { MimeMultipart container = this.getContainer(); MimeMultipart subContainer = null; MimeMultipart subContainerHTML = new MimeMultipart("related"); BodyPart msgHtml = null; BodyPart msgText = null; container.setSubType("mixed"); subContainer = new MimeMultipart("alternative"); if (!StringUtil.isEmpty(this.text)) { msgText = new MimeBodyPart(); subContainer.addBodyPart(msgText); if (!StringUtil.isEmpty(this.charset)) { msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset); } else { msgText.setContent(this.text, Email.TEXT_PLAIN); } } if (!StringUtil.isEmpty(this.html)) { if (this.inlineImages.size() > 0) { msgHtml = new MimeBodyPart(); subContainerHTML.addBodyPart(msgHtml); } else { msgHtml = new MimeBodyPart(); subContainer.addBodyPart(msgHtml); } if (!StringUtil.isEmpty(this.charset)) { msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset); } else { msgHtml.setContent(this.html, Email.TEXT_HTML); } Iterator iter = this.inlineImages.iterator(); while (iter.hasNext()) { subContainerHTML.addBodyPart((BodyPart) iter.next()); } } // add sub containers to message this.addPart(subContainer, 0); if (this.inlineImages.size() > 0) { // add sub container to message this.addPart(subContainerHTML, 1); } }
From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java
/**Enwrapps the data into a signed MIME message structure and returns it*/ private void enwrappInMessageAndSign(AS2Message message, Part contentPart, Partner sender, Partner receiver) throws Exception { AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info(); MimeMessage messagePart = new MimeMessage(Session.getInstance(System.getProperties(), null)); //sign message if this is requested if (info.getSignType() != AS2Message.SIGNATURE_NONE) { MimeMultipart signedPart = this.signContentPart(contentPart, sender, receiver); if (this.logger != null) { String signAlias = this.signatureCertManager.getAliasByFingerprint(sender.getSignFingerprintSHA1()); this.logger.log(Level.INFO, this.rb.getResourceString("message.signed", new Object[] { info.getMessageId(), signAlias, this.rbMessage.getResourceString("signature." + receiver.getSignType()) }), info);//from www.ja v a 2 s . c om } messagePart.setContent(signedPart); messagePart.saveChanges(); } else { //unsigned message if (contentPart instanceof MimeBodyPart) { MimeMultipart unsignedPart = new MimeMultipart(); unsignedPart.addBodyPart((MimeBodyPart) contentPart); if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("message.notsigned", new Object[] { info.getMessageId() }), info); } messagePart.setContent(unsignedPart); } else if (contentPart instanceof MimeMultipart) { messagePart.setContent((MimeMultipart) contentPart); } else if (contentPart instanceof MimeMessage) { messagePart = (MimeMessage) contentPart; } else { throw new IllegalArgumentException("enwrappInMessageAndSign: Unable to set the content of a " + contentPart.getClass().getName()); } messagePart.saveChanges(); } //store signed or unsigned data ByteArrayOutputStream signedOut = new ByteArrayOutputStream(); //normally the content type header is folded (which is correct but some products are not able to parse this properly) //Now take the content-type, unfold it and write it Enumeration headerLines = messagePart.getMatchingHeaderLines(new String[] { "Content-Type" }); LineOutputStream los = new LineOutputStream(signedOut); while (headerLines.hasMoreElements()) { //requires java mail API >= 1.4 String nextHeaderLine = MimeUtility.unfold((String) headerLines.nextElement()); //write the line only if the as2 message is encrypted. If the as2 message is unencrypted this header is added later //in the class MessageHttpUploader if (info.getEncryptionType() != AS2Message.ENCRYPTION_NONE) { los.writeln(nextHeaderLine); } //store the content line in the as2 message object, this value is required later in MessageHttpUploader message.setContentType(nextHeaderLine.substring(nextHeaderLine.indexOf(':') + 1)); } messagePart.writeTo(signedOut, new String[] { "Message-ID", "Mime-Version", "Content-Type" }); signedOut.flush(); signedOut.close(); message.setDecryptedRawData(signedOut.toByteArray()); }
From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java
private void sendEmail(boolean test, AmazonSimpleEmailServiceClient emailService, String email, List<ApplicationGroup> appGroups) throws IOException, MessagingException { StringBuilder body = new StringBuilder(); body.append(/* ww w. j av a 2s.com*/ "<html><head><style type=\"text/css\">a:link, a:visited{color:#006DBA;}a:link, a:visited, a:hover {\n" + "text-decoration: none;\n" + "}\n" + "body {\n" + "color: #333;\n" + "}" + "</style></head>"); List<MimeBodyPart> mimeBodyParts = Lists.newArrayList(); int index = 0; String subject = ""; for (ApplicationGroup appGroup : appGroups) { boolean hasData = false; for (String prodName : appGroup.data.keySet()) { if (config.productService.getProductByName(prodName) == null) continue; hasData = appGroup.data.get(prodName) != null && appGroup.data.get(prodName).size() > 0; if (hasData) break; } if (!hasData) continue; try { MimeBodyPart mimeBodyPart = constructEmail(index, appGroup, body); index++; if (mimeBodyPart != null) { mimeBodyParts.add(mimeBodyPart); subject = subject + (subject.length() > 0 ? ", " : "") + appGroup.getDisplayName(); } } catch (Exception e) { logger.error("Error contructing email", e); } } body.append("</html>"); if (mimeBodyParts.size() == 0) return; DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0); subject = String.format("%s Weekly AWS Costs (%s - %s)", subject, formatter.print(end.minusWeeks(1)), formatter.print(end)); String toEmail = test ? testEmail : email; Session session = Session.getInstance(new Properties()); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject(subject); mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, toEmail); if (!test && !StringUtils.isEmpty(bccEmail)) { mimeMessage.addRecipients(Message.RecipientType.BCC, bccEmail); } MimeMultipart mimeMultipart = new MimeMultipart(); BodyPart p = new MimeBodyPart(); p.setContent(body.toString(), "text/html"); mimeMultipart.addBodyPart(p); for (MimeBodyPart mimeBodyPart : mimeBodyParts) mimeMultipart.addBodyPart(mimeBodyPart); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); mimeMessage.setContent(mimeMultipart); mimeMessage.writeTo(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage); rawEmailRequest.setDestinations(Lists.<String>newArrayList(toEmail)); rawEmailRequest.setSource(fromEmail); logger.info("sending email to " + toEmail + " " + body.toString()); emailService.sendRawEmail(rawEmailRequest); }
From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java
/** * Helper function to create multi-part MIME * * @param entity the body of a request * @param entityContentType content type of the body * @param query a query part of a request * * @return a ByteString that represents a multi-part encoded entity that contains both *///from www. j av a2s .co m private static MimeMultipart createMultiPartEntity(final ByteString entity, final String entityContentType, String query) throws MessagingException { MimeMultipart multi = new MimeMultipart(MIXED); // Create current entity with the associated type MimeBodyPart dataPart = new MimeBodyPart(); ContentType contentType = new ContentType(entityContentType); if (MULTIPART.equals(contentType.getBaseType())) { MimeMultipart nested = new MimeMultipart(new DataSource() { @Override public InputStream getInputStream() throws IOException { return entity.asInputStream(); } @Override public OutputStream getOutputStream() throws IOException { return null; } @Override public String getContentType() { return entityContentType; } @Override public String getName() { return null; } }); dataPart.setContent(nested, contentType.getBaseType()); } else { dataPart.setContent(entity.copyBytes(), contentType.getBaseType()); } dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType); // Encode query params as form-urlencoded MimeBodyPart argPart = new MimeBodyPart(); argPart.setContent(query, FORM_URL_ENCODED); argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED); multi.addBodyPart(argPart); multi.addBodyPart(dataPart); return multi; }
From source file:com.aurel.track.util.emailHandling.MailBuilder.java
private void includeAttachments(MimeMultipart mimeMultipart, List<LabelValueBean> attachments) throws MessagingException { for (int i = 0; i < attachments.size(); i++) { LabelValueBean lvb = attachments.get(i); File f = new File(lvb.getValue()); if (f != null && f.exists()) { LOGGER.debug("Use attachment file:" + f.getAbsolutePath()); MimeBodyPart mbpFile = new MimeBodyPart(); FileDataSource fds = new FileDataSource(f); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(lvb.getLabel()); mimeMultipart.addBodyPart(mbpFile); } else {/*from w w w . j av a2s .c o m*/ LOGGER.debug("Attachment file:\"" + lvb.getValue() + "\" not exits!"); } } }
From source file:com.googlecode.ddom.mime.JavaMailTest.java
private void test(boolean preamble) throws Exception { MimeMultipart multipart = new MimeMultipart(); MimeBodyPart bodyPart1 = new MimeBodyPart(); StringBuilder buffer = new StringBuilder(); for (int i = 0; i < 1000; i++) { buffer.append('('); buffer.append(i);/*from w w w. ja v a 2s . c o m*/ buffer.append(')'); } String content1 = buffer.toString(); bodyPart1 .setDataHandler(new DataHandler(new ByteArrayDataSource(content1.getBytes("UTF-8"), "text/plain"))); Map<String, String> headers1 = new HashMap<String, String>(); headers1.put("Content-ID", "<1@example.com>"); headers1.put("Content-Type", "text/plain; charset=UTF-8"); setHeaders(bodyPart1, headers1); multipart.addBodyPart(bodyPart1); MimeBodyPart bodyPart2 = new MimeBodyPart(); byte[] content2 = new byte[10000]; new Random().nextBytes(content2); bodyPart2.setDataHandler(new DataHandler(new ByteArrayDataSource(content2, "application/octet-stream"))); Map<String, String> headers2 = new HashMap<String, String>(); headers2.put("Content-ID", "<2@example.com>"); headers2.put("Content-Type", "application/octet-stream"); setHeaders(bodyPart2, headers2); multipart.addBodyPart(bodyPart2); if (preamble) { multipart.setPreamble("This is a MIME multipart."); } String boundary = new ContentType(multipart.getContentType()).getParameter("boundary"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); multipart.writeTo(baos); MultipartReader mpr = new MultipartReader(new ByteArrayInputStream(baos.toByteArray()), boundary); assertTrue(mpr.nextPart()); assertEquals(headers1, readHeaders(mpr)); assertEquals(content1, IOUtils.toString(mpr.getContent(), "UTF-8")); assertTrue(mpr.nextPart()); assertEquals(headers2, readHeaders(mpr)); assertArrayEquals(content2, IOUtils.toByteArray(mpr.getContent())); assertFalse(mpr.nextPart()); }
From source file:it.cnr.icar.eric.common.RepositoryItemImpl.java
/** * Packages the RepositoryItem as a MimeMultiPart and returns it * * @deprecated sigElement/multipart attachment is not used anymore. *//* ww w . jav a 2 s .c o m*/ public MimeMultipart getMimeMultipart() throws RegistryException { MimeMultipart mp = null; try { //Create a multipart with two bodyparts //First bodypart is an XMLDSIG and second is the attached file mp = new MimeMultipart(); //The signature part ByteArrayOutputStream os = new ByteArrayOutputStream(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.transform(new DOMSource(sigElement), new StreamResult(os)); MimeBodyPart bp1 = new MimeBodyPart(); bp1.addHeader("Content-ID", "payload1"); bp1.setText(os.toString(), "utf-8"); mp.addBodyPart(bp1); //The payload part MimeBodyPart bp2 = new MimeBodyPart(); bp2.setDataHandler(handler); bp2.addHeader("Content-Type", handler.getContentType()); bp2.addHeader("Content-ID", "payload2"); mp.addBodyPart(bp2); } catch (MessagingException e) { throw new RegistryException(e); } catch (TransformerException e) { throw new RegistryException(e); } return mp; }
From source file:fsi_admin.JSmtpConn.java
private boolean prepareMsg(String FROM, String TO, String SUBJECT, String MIMETYPE, String BODY, StringBuffer msj, Properties props, Session session, MimeMessage mmsg, BodyPart messagebodypart, MimeMultipart multipart) { // Create a message with the specified information. try {/*from ww w .j a v a 2 s .co m*/ mmsg.setFrom(new InternetAddress(FROM)); mmsg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO)); mmsg.setSubject(SUBJECT); messagebodypart.setContent(BODY, MIMETYPE); multipart.addBodyPart(messagebodypart); return true; } catch (AddressException e) { e.printStackTrace(); msj.append("Error de Direcciones al preparar SMTP: " + e.getMessage()); return false; } catch (MessagingException e) { e.printStackTrace(); msj.append("Error de Mensajeria al preparar SMTP: " + e.getMessage()); return false; } }
From source file:com.adaptris.mail.MailSenderImp.java
private void addAttachmentsToMessage(MimeMultipart multipart) throws MailException { try {/*w w w . j ava 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:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java
private void sendEmail(Map<String, String> templatesParams, List<BodyPart> attachments, String toAddress) throws MessagingException { MimeBodyPart htmlAndPlainTextAlternativeBody = new MimeBodyPart(); // TEXT AND HTML MESSAGE (gmail requires plain text alternative, otherwise, it displays the 1st plain text attachment in the preview) MimeMultipart cover = new MimeMultipart("alternative"); htmlAndPlainTextAlternativeBody.setContent(cover); BodyPart textHtmlBodyPart = new MimeBodyPart(); String textHtmlBody = FreemarkerUtils.generate(templatesParams, "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier() + ".html.ftl"); textHtmlBodyPart.setContent(textHtmlBody, "text/html"); cover.addBodyPart(textHtmlBodyPart); BodyPart textPlainBodyPart = new MimeBodyPart(); cover.addBodyPart(textPlainBodyPart); String textPlainBody = FreemarkerUtils.generate(templatesParams, "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier() + ".txt.ftl"); textPlainBodyPart.setContent(textPlainBody, "text/plain"); MimeMultipart content = new MimeMultipart("related"); content.addBodyPart(htmlAndPlainTextAlternativeBody); // ATTACHMENTS for (BodyPart bodyPart : attachments) { content.addBodyPart(bodyPart);/*from w ww .j a va2s .c o m*/ } MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(mailFrom); msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress)); msg.addRecipient(javax.mail.Message.RecipientType.CC, mailFrom); String subject = "[Xebia Amazon AWS " + environment.getIdentifier() + "] Credentials"; msg.setSubject(subject); msg.setContent(content); mailTransport.sendMessage(msg, msg.getAllRecipients()); }