List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart
public MimeBodyPart()
From source file:no.kantega.publishing.modules.mailsender.MailSender.java
/** * Helper method to create a MimeBodyPart from a binary file. * * @param data Data// w ww.ja v a2s.c o m * @param contentType The Mime content type of the file. * @param fileName The name of the file - as it will appear for the mail recipient. * @return The resulting MimeBodyPart. * @throws SystemException if the MimeBodyPart can't be created. */ public static MimeBodyPart createMimeBodyPartFromData(byte[] data, final String contentType, String fileName) throws SystemException { try { MimeBodyPart attachmentPart1 = new MimeBodyPart(); ByteArrayDataSource dataSource = new ByteArrayDataSource(data, contentType) { @Override public String getContentType() { return contentType; } }; attachmentPart1.setDataHandler(new DataHandler(dataSource)); attachmentPart1.setFileName(fileName); return attachmentPart1; } catch (MessagingException e) { throw new SystemException("Feil ved generering av MimeBodyPart fra data[]", e); } }
From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java
/** * Creates a Multipart MIME Message (multiple content-types within the same message) from an existing mail * /*from w w w . j a v a 2 s. c o m*/ * @param mail The original Mail * @return The Multipart MIME message */ public Multipart createMimeMultipart(Mail mail, XWikiContext context) throws MessagingException, XWikiException, IOException { Multipart multipart; List<Attachment> rawAttachments = mail.getAttachments() != null ? mail.getAttachments() : new ArrayList<Attachment>(); if (mail.getHtmlPart() == null && mail.getAttachments() != null) { multipart = new MimeMultipart("mixed"); // Create the text part of the email BodyPart textPart = new MimeBodyPart(); textPart.setContent(mail.getTextPart(), "text/plain; charset=" + EMAIL_ENCODING); multipart.addBodyPart(textPart); // Add attachments to the main multipart for (Attachment attachment : rawAttachments) { multipart.addBodyPart(createAttachmentBodyPart(attachment, context)); } } else { multipart = new MimeMultipart("mixed"); List<Attachment> attachments = new ArrayList<Attachment>(); List<Attachment> embeddedImages = new ArrayList<Attachment>(); // Create the text part of the email BodyPart textPart; textPart = new MimeBodyPart(); textPart.setText(mail.getTextPart()); // Create the HTML part of the email, define the html as a multipart/related in case there are images Multipart htmlMultipart = new MimeMultipart("related"); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(mail.getHtmlPart(), "text/html; charset=" + EMAIL_ENCODING); htmlPart.setHeader("Content-Disposition", "inline"); htmlPart.setHeader("Content-Transfer-Encoding", "quoted-printable"); htmlMultipart.addBodyPart(htmlPart); // Find images used with src="cid:" in the email HTML part Pattern cidPattern = Pattern.compile("src=('|\")cid:([^'\"]*)('|\")", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); Matcher matcher = cidPattern.matcher(mail.getHtmlPart()); List<String> foundEmbeddedImages = new ArrayList<String>(); while (matcher.find()) { foundEmbeddedImages.add(matcher.group(2)); } // Loop over the attachments of the email, add images used from the HTML to the list of attachments to be // embedded with the HTML part, add the other attachements to the list of attachments to be attached to the // email. for (Attachment attachment : rawAttachments) { if (foundEmbeddedImages.contains(attachment.getFilename())) { embeddedImages.add(attachment); } else { attachments.add(attachment); } } // Add the images to the HTML multipart (they should be hidden from the mail reader attachment list) for (Attachment image : embeddedImages) { htmlMultipart.addBodyPart(createAttachmentBodyPart(image, context)); } // Wrap the HTML and text parts in an alternative body part and add it to the main multipart Multipart alternativePart = new MimeMultipart("alternative"); BodyPart alternativeMultipartWrapper = new MimeBodyPart(); BodyPart htmlMultipartWrapper = new MimeBodyPart(); alternativePart.addBodyPart(textPart); htmlMultipartWrapper.setContent(htmlMultipart); alternativePart.addBodyPart(htmlMultipartWrapper); alternativeMultipartWrapper.setContent(alternativePart); multipart.addBodyPart(alternativeMultipartWrapper); // Add attachments to the main multipart for (Attachment attachment : attachments) { multipart.addBodyPart(createAttachmentBodyPart(attachment, context)); } } return multipart; }
From source file:org.apache.nifi.processors.standard.PutEmail.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final FlowFile flowFile = session.get(); if (flowFile == null) { return;/*from w ww . j a v a 2s . c om*/ } final Properties properties = this.getMailPropertiesFromFlowFile(context, flowFile); final Session mailSession = this.createMailSession(properties); final Message message = new MimeMessage(mailSession); final ComponentLog logger = getLogger(); try { message.addFrom(toInetAddresses(context, flowFile, FROM)); message.setRecipients(RecipientType.TO, toInetAddresses(context, flowFile, TO)); message.setRecipients(RecipientType.CC, toInetAddresses(context, flowFile, CC)); message.setRecipients(RecipientType.BCC, toInetAddresses(context, flowFile, BCC)); message.setHeader("X-Mailer", context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions(flowFile).getValue()); message.setSubject(context.getProperty(SUBJECT).evaluateAttributeExpressions(flowFile).getValue()); String messageText = context.getProperty(MESSAGE).evaluateAttributeExpressions(flowFile).getValue(); if (context.getProperty(INCLUDE_ALL_ATTRIBUTES).asBoolean()) { messageText = formatAttributes(flowFile, messageText); } String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions(flowFile) .getValue(); message.setContent(messageText, contentType); message.setSentDate(new Date()); if (context.getProperty(ATTACH_FILE).asBoolean()) { final MimeBodyPart mimeText = new PreencodedMimeBodyPart("base64"); mimeText.setDataHandler(new DataHandler(new ByteArrayDataSource( Base64.encodeBase64(messageText.getBytes("UTF-8")), contentType + "; charset=\"utf-8\""))); final MimeBodyPart mimeFile = new MimeBodyPart(); session.read(flowFile, new InputStreamCallback() { @Override public void process(final InputStream stream) throws IOException { try { mimeFile.setDataHandler( new DataHandler(new ByteArrayDataSource(stream, "application/octet-stream"))); } catch (final Exception e) { throw new IOException(e); } } }); mimeFile.setFileName(flowFile.getAttribute(CoreAttributes.FILENAME.key())); MimeMultipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeText); multipart.addBodyPart(mimeFile); message.setContent(multipart); } send(message); session.getProvenanceReporter().send(flowFile, "mailto:" + message.getAllRecipients()[0].toString()); session.transfer(flowFile, REL_SUCCESS); logger.info("Sent email as a result of receiving {}", new Object[] { flowFile }); } catch (final ProcessException | MessagingException | IOException e) { context.yield(); logger.error("Failed to send email for {}: {}; routing to failure", new Object[] { flowFile, e.getMessage() }, e); session.transfer(flowFile, REL_FAILURE); } }
From source file:com.szmslab.quickjavamail.send.MailSender.java
/** * MimeBodyPart????Content-Disposition: inline * * @param file/*from ww w.ja v a 2 s .c o m*/ * ? * @return MimeBodyPartContent-Disposition: inline? * @throws MessagingException * @throws UnsupportedEncodingException */ private MimeBodyPart createImagePart(InlineImageFile file) throws MessagingException, UnsupportedEncodingException { MimeBodyPart imagePart = new MimeBodyPart(); imagePart.setContentID(file.getContentId()); imagePart.setFileName(MimeUtility.encodeText(file.getFileName(), charset, null)); imagePart.setDataHandler(new DataHandler(file.getDataSource())); imagePart.setDisposition(MimeBodyPart.INLINE); return imagePart; }
From source file:org.silverpeas.core.mail.SmtpMailSendingTest.java
@Test public void sendingMailSynchronouslyValidMailWithReplyTo(GreenMailOperations mail) throws Exception { MailAddress senderEmail = MailAddress.eMail(COMMON_FROM).withName("From Personal Name"); MailAddress receiverEmail = MailAddress.eMail(COMMON_TO).withName("To Personal Name"); String subject = "A subject"; Multipart content = new MimeMultipart(); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent("A content", MimeTypes.HTML_MIME_TYPE); content.addBodyPart(mimeBodyPart);//from w w w . j av a2 s.c o m MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject) .withContent(content).setReplyToRequired(); // Sending mail mailSending.sendSynchronously(); // Verifying sent data MailToSend mailToSend = getStubbedSmtpMailSender().currentMailToSend; assertThat(mailToSend.getFrom(), is(senderEmail)); assertThat(mailToSend.getTo(), hasItem(receiverEmail)); assertThat(mailToSend.getSubject(), is(subject)); assertThat(mailToSend.getContent().isHtml(), is(true)); assertThat(mailToSend.getContent().toString(), is(content.toString())); assertThat(mailToSend.isReplyToRequired(), is(true)); assertThat(mailToSend.isAsynchronous(), is(false)); assertMailSent(mailToSend, mail); }
From source file:org.exoplatform.extension.social.notifications.SocialNotificationService.java
/** * /*www.ja va2 s .c o m*/ * @param space * @param managers * @param pendingUsers */ private void pendingUserNotification(Space space, List<Profile> managerList, List<Profile> pendingUsers) { //TODO : use groovy template stored in JCR for mail information (cleaner, real templating) log.info("Sending mail to space manager : pending users"); try { // loop on each manager and send mail // like that each manager will have the mail in its preferred language // ideally should be done in a different executor // TODO: see if we can optimize this to avoid do it for all user // - send a mail to all the users in the same time (what about language) // - cache the template result and send mail for (Profile manager : managerList) { Locale locale = Locale.getDefault(); // get default locale of the manager String userId = manager.getIdentity().getRemoteId(); String userLocale = this.getOrganizationService().getUserProfileHandler() .findUserProfileByName(userId).getAttribute("user.language"); if (userLocale != null && !userLocale.trim().isEmpty()) { locale = new Locale(userLocale); } // getMessageTemplate MessageTemplate messageTemplate = this.getMailMessageTemplate( SocialNotificationConfiguration.MAIL_TEMPLATE_SPACE_PENDING_USERS, locale); GroovyTemplate g = new GroovyTemplate(messageTemplate.getSubject()); String spaceUrl = this.getPortalUrl() + "/portal/g/:spaces:" + space.getUrl() + "/" + space.getUrl() + "/settings"; //TODO: see which API to use String spaceAvatarUrl = null; if (space.getAvatarUrl() != null) { spaceAvatarUrl = this.getPortalUrl() + space.getAvatarUrl(); } Map binding = new HashMap(); binding.put("space", space); binding.put("portalUrl", this.getPortalUrl()); binding.put("spaceSettingUrl", spaceUrl); binding.put("spaceAvatarUrl", spaceAvatarUrl); binding.put("userPendingList", pendingUsers); String subject = g.render(binding); g = new GroovyTemplate(messageTemplate.getHtmlContent()); String htmlContent = g.render(binding); g = new GroovyTemplate(messageTemplate.getPlainTextContent()); String textContent = g.render(binding); MailService mailService = this.getMailService(); Session mailSession = mailService.getMailSession(); MimeMessage message = new MimeMessage(mailSession); message.setFrom(this.getSenderAddress()); // send email to manager message.setRecipient(RecipientType.TO, new InternetAddress(manager.getEmail(), manager.getFullName())); message.setSubject(subject); MimeMultipart content = new MimeMultipart("alternative"); MimeBodyPart text = new MimeBodyPart(); MimeBodyPart html = new MimeBodyPart(); text.setText(textContent); html.setContent(htmlContent, "text/html; charset=ISO-8859-1"); content.addBodyPart(text); content.addBodyPart(html); message.setContent(content); log.info("Sending mail to" + manager.getEmail() + " : " + subject + " : " + subject + "\n" + html); //mailService.sendMessage(message); } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.apache.james.transport.mailets.DSNBounce.java
private MimeBodyPart createTextMsg(Mail originalMail) throws MessagingException { StringBuffer buffer = new StringBuffer(); buffer.append(bounceMessage()).append(LINE_BREAK); buffer.append("Failed recipient(s):").append(LINE_BREAK); for (MailAddress mailAddress : originalMail.getRecipients()) { buffer.append(mailAddress);// w w w . j a v a 2 s .com } buffer.append(LINE_BREAK).append(LINE_BREAK); buffer.append("Error message:").append(LINE_BREAK); buffer.append((String) originalMail.getAttribute("delivery-error")).append(LINE_BREAK); buffer.append(LINE_BREAK); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(buffer.toString()); return bodyPart; }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail.//from w w w . ja v a2s .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:org.apache.jsieve.mailet.SieveMailboxMailet.java
/** * Deliver the original mail as an attachment with the main part being an error report. * * @param recipient/*from w ww. ja v a 2s .c o m*/ * @param aMail * @param ex * @throws MessagingException * @throws IOException */ protected void handleFailure(MailAddress recipient, Mail aMail, Exception ex) throws MessagingException, IOException { String user = getUsername(recipient); MimeMessage originalMessage = aMail.getMessage(); MimeMessage message = new MimeMessage(originalMessage); MimeMultipart multipart = new MimeMultipart(); MimeBodyPart noticePart = new MimeBodyPart(); noticePart.setText(new StringBuilder().append( "An error was encountered while processing this mail with the active sieve script for user \"") .append(user).append("\". The error encountered was:\r\n").append(ex.getLocalizedMessage()) .append("\r\n").toString()); multipart.addBodyPart(noticePart); MimeBodyPart originalPart = new MimeBodyPart(); originalPart.setContent(originalMessage, "message/rfc822"); if ((originalMessage.getSubject() != null) && (!originalMessage.getSubject().trim().isEmpty())) { originalPart.setFileName(originalMessage.getSubject().trim()); } else { originalPart.setFileName("No Subject"); } originalPart.setDisposition(MimeBodyPart.INLINE); multipart.addBodyPart(originalPart); message.setContent(multipart); message.setSubject("[SIEVE ERROR] " + originalMessage.getSubject()); message.setHeader("X-Priority", "1"); message.saveChanges(); storeMessageInbox(user, message); }
From source file:com.openkm.util.MailUtils.java
/** * Create a mail.//from w ww.j a va 2 s. c om * * @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; }