List of usage examples for javax.mail.internet MimeMultipart MimeMultipart
public MimeMultipart(DataSource ds) throws MessagingException
From source file:org.xwiki.mail.integration.JavaIntegrationTest.java
@Test public void sendTextMail() throws Exception { // Step 1: Create a JavaMail Session Session session = Session.getInstance(this.configuration.getAllProperties()); // Step 2: Create the Message to send MimeMessage message = new MimeMessage(session); message.setSubject("subject"); message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com")); // Step 3: Add the Message Body Multipart multipart = new MimeMultipart("mixed"); // Add text in the body multipart.addBodyPart(this.defaultBodyPartFactory.create("some text here", Collections.<String, Object>singletonMap("mimetype", "text/plain"))); message.setContent(multipart);//from www . j av a 2s . co m // We also test using some default BCC addresses from configuration in this test this.configuration.setBCCAddresses(Arrays.asList("bcc1@doe.com", "bcc2@doe.com")); // Ensure we do not reuse the same message identifier for multiple similar messages in this test MimeMessage message2 = new MimeMessage(message); message2.saveChanges(); MimeMessage message3 = new MimeMessage(message); message3.saveChanges(); // Step 4: Send the mail and wait for it to be sent // Send 3 mails (3 times the same mail) to verify we can send several emails at once. MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory"); this.sender.sendAsynchronously(Arrays.asList(message, message2, message3), session, memoryMailListener); // Note: we don't test status reporting from the listener since this is already tested in the // ScriptingIntegrationTest test class. // Verify that the mails have been received (wait maximum 30 seconds). this.mail.waitForIncomingEmail(30000L, 3); MimeMessage[] messages = this.mail.getReceivedMessages(); // Note: we're receiving 9 messages since we sent 3 with 3 recipients (2 BCC and 1 to)! assertEquals(9, messages.length); // Assert the email parts that are the same for all mails assertEquals("subject", messages[0].getHeader("Subject", null)); assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount()); BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0); assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]); assertEquals("some text here", textBodyPart.getContent()); assertEquals("john@doe.com", messages[0].getHeader("To", null)); // Note: We cannot assert that the BCC worked since by definition BCC information are not visible in received // messages ;) But we checked that we received 9 emails above so that's good enough. }
From source file:com.zacwolf.commons.email.Email.java
public Multipart getAsMultipart() throws MessagingException { /** First we create the "related" htmlmultipart for the html email content: * ?/*from w w w . jav a2s. c o m*/ * msg.setContent() * ? * htmlmultipart [MimeMultipart("related")] * ? * htmlmessageBodyPart [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * EmailAttachment(INLINE) [BodyPart] * * * **/ final Multipart htmlmultipart = new MimeMultipart("related"); final BodyPart htmlmessageBodyPart = new MimeBodyPart(); htmlmultipart.addBodyPart(htmlmessageBodyPart); final org.jsoup.nodes.Document doc = Jsoup.parse(getBody(), "UTF-8"); prepareImgs(doc, htmlmultipart); prepare(doc); htmlmessageBodyPart.setContent(doc.toString(), "text/html; charset=utf-8"); // populate the top multipart Multipart msgmultipart = htmlmultipart; if (getBodyPlainText() != null) {// Now create a plain-text body part /** * If there is a plain text attachment (and their should always be one), * then an "alternative" type MimeMultipart is added to the structure * ? * msg.setContent() * ? * msgmultipart [MimeMultipart("alternative")] * ? * htmlcontent [MimeBodyPart] * ? * htmlmultipart [MimeMultipart("related")] * ? * htmlmessageBodyPart [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * * * plaintxtBodypart [MimeBodyPart] * .setText(message_plaintxt) * * * */ msgmultipart = new MimeMultipart("alternative"); final BodyPart plaintxtBodyPart = new MimeBodyPart(); plaintxtBodyPart.setText(getBodyPlainText()); final BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(htmlmultipart); msgmultipart.addBodyPart(plaintxtBodyPart); msgmultipart.addBodyPart(htmlBodyPart); } /** * If there are non-inline attachments, then a "mixed" type * MimeMultipart object has to be added to the structure * ? * msg.setContent() * ? * msgmultipart [MimeMultipart("mixed")] * ? * wrap [MimeBodyPart] * ? * msgmultipart [MimeMultipart("alternative")] * ? * htmlcontent [MimeBodyPart] * ? * htmlmultipart [MimeMultipart("related")] * ? * htmlmessageBodyPart [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * * * plaintxtBodypart [MimeBodyPart] * .setText(message_plaintxt) * * * * EmailAttachment (non-inline) [MimeBodyPart] * * EmailAttachment (non-inline) [MimeBodyPart] * * * */ Multipart mixed = msgmultipart; final Set<EmailAttachment> noninlineattachments = new HashSet<EmailAttachment>(); for (EmailAttachment attach : getAttachments().values()) if (attach.disposition != null && !attach.disposition.equals(MimeBodyPart.INLINE)) noninlineattachments.add(attach); // If there are non-IN-LINE attachments, we'll have to create another layer "mixed" MultiPart object if (!noninlineattachments.isEmpty()) { mixed = new MimeMultipart("mixed"); //Multiparts are not themselves containers, so create a wrapper BodyPart container final BodyPart wrap = new MimeBodyPart(); wrap.setContent(msgmultipart); mixed.addBodyPart(wrap); for (EmailAttachment attach : noninlineattachments) mixed.addBodyPart(attach); } return mixed; }
From source file:lucee.runtime.net.mail.HtmlEmailImpl.java
/** * @throws EmailException EmailException * @throws MessagingException MessagingException *//* w w w. j av a2 s .co m*/ private void buildNoAttachments() throws MessagingException, EmailException { MimeMultipart container = this.getContainer(); MimeMultipart subContainerHTML = new MimeMultipart("related"); container.setSubType("alternative"); BodyPart msgText = null; BodyPart msgHtml = null; if (!StringUtil.isEmpty(this.text)) { msgText = this.getPrimaryBodyPart(); 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 the txt part of the message was null, then the html part // will become the primary body part if (msgText == null) { msgHtml = getPrimaryBodyPart(); } else { if (this.inlineImages.size() > 0) { msgHtml = new MimeBodyPart(); subContainerHTML.addBodyPart(msgHtml); } else { msgHtml = new MimeBodyPart(); container.addBodyPart(msgHtml, 1); } } 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()); } if (this.inlineImages.size() > 0) { // add sub container to message this.addPart(subContainerHTML); } } }
From source file:org.tizzit.util.mail.MailHelper.java
/** * Send an email in html-format in iso-8859-1-encoding * /*from www .j a v a 2 s . c o m*/ * @param subject the subject of the new mail * @param htmlMessage the content of the mail as html * @param alternativeTextMessage the content of the mail as text * @param from the sender-address * @param to the receiver-address * @param cc the address of the receiver of a copy of this mail * @param bcc the address of the receiver of a blind-copy of this mail */ public static void sendHtmlMail2(String subject, String htmlMessage, String alternativeTextMessage, String from, String[] to, String[] cc, String[] bcc) { try { MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); if (cc != null && cc.length != 0) { for (int i = cc.length - 1; i >= 0; i--) { msg.addRecipients(Message.RecipientType.CC, cc[i]); } } if (bcc != null && bcc.length != 0) { for (int i = bcc.length - 1; i >= 0; i--) { msg.addRecipients(Message.RecipientType.BCC, bcc[i]); } } if (to != null && to.length != 0) { for (int i = to.length - 1; i >= 0; i--) { msg.addRecipients(Message.RecipientType.TO, to[i]); } } msg.setSubject(subject, "ISO8859_1"); msg.setSentDate(new Date()); MimeMultipart multiPart = new MimeMultipart("alternative"); MimeBodyPart htmlPart = new MimeBodyPart(); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(alternativeTextMessage, "ISO8859_1"); textPart.setHeader("MIME-Version", "1.0"); //textPart.setHeader("Content-Type", textPart.getContentType()); textPart.setHeader("Content-Type", "text/plain;charset=\"ISO-8859-1\""); htmlPart.setContent(htmlMessage, "text/html;charset=\"ISO8859_1\""); htmlPart.setHeader("MIME-Version", "1.0"); htmlPart.setHeader("Content-Type", "text/html;charset=\"ISO-8859-1\""); //htmlPart.setHeader("Content-Type", htmlPart.getContentType()); multiPart.addBodyPart(textPart); multiPart.addBodyPart(htmlPart); multiPart.setSubType("alternative"); msg.setContent(multiPart); msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", multiPart.getContentType()); Transport.send(msg); } catch (Exception e) { log.error("Error sending html-mail: " + e.getLocalizedMessage()); } }
From source file:org.sakaiproject.nakamura.smtp.SakaiSmtpServer.java
@SuppressWarnings("unchecked") private Content writeMessage(Session session, Map<String, Object> mapProperties, InputStream data, String storePath)//ww w .j a v a2s. c o m throws MessagingException, AccessDeniedException, StorageClientException, IOException { InternetHeaders internetHeaders = new InternetHeaders(data); // process the headers into a map. for (Enumeration<Header> e = internetHeaders.getAllHeaders(); e.hasMoreElements();) { Header h = e.nextElement(); String name = h.getName(); String[] values = internetHeaders.getHeader(name); if (values != null) { if (values.length == 1) { mapProperties.put("sakai:" + name.toLowerCase(), values[0]); } else { mapProperties.put("sakai:" + name.toLowerCase(), values); } } } String[] contentType = internetHeaders.getHeader("content-type"); if (contentType != null && contentType.length > 0 && contentType[0].contains("boundary") && contentType[0].contains("multipart/")) { MimeMultipart multipart = new MimeMultipart(new SMTPDataSource(contentType[0], data)); Content message = messagingService.create(session, mapProperties, (String) mapProperties.get("sakai:message-id"), storePath); writeMultipartToNode(session, message, multipart); return message; } else { Content node = messagingService.create(session, mapProperties); // set up to stream the body. session.getContentManager().writeBody(node.getPath(), data); return node; } }
From source file:org.pentaho.platform.util.Emailer.java
public boolean send() { String from = props.getProperty("mail.from.default"); String fromName = props.getProperty("mail.from.name"); String to = props.getProperty("to"); String cc = props.getProperty("cc"); String bcc = props.getProperty("bcc"); boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth")); String subject = props.getProperty("subject"); String body = props.getProperty("body"); logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject + "' and the body " + body); try {/*w w w . j a va2 s. com*/ // Get a Session object Session session; if (authenticate) { session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // if debugging is not set in the email config file, then default to false if (!props.containsKey("mail.debug")) { //$NON-NLS-1$ session.setDebug(false); } final MimeMessage msg; if (EMBEDDED_HTML.equals(attachmentMimeType)) { //Message is ready msg = new MimeMessage(session, attachment); if (body != null) { //We need to add message to the top of the email body final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent(); final MimeMultipart newMultipart = new MimeMultipart("related"); for (int i = 0; i < oldMultipart.getCount(); i++) { BodyPart bodyPart = oldMultipart.getBodyPart(i); final Object content = bodyPart.getContent(); //Main HTML body if (content instanceof String) { final String newContent = body + "<br/><br/>" + content; final MimeBodyPart part = new MimeBodyPart(); part.setText(newContent, "UTF-8", "html"); newMultipart.addBodyPart(part); } else { //CID attachments newMultipart.addBodyPart(bodyPart); } } msg.setContent(newMultipart); } } else { // construct the message msg = new MimeMessage(session); Multipart multipart = new MimeMultipart(); if (attachment == null) { logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$ return false; } ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType); if (body != null) { MimeBodyPart bodyMessagePart = new MimeBodyPart(); bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding()); multipart.addBodyPart(bodyMessagePart); } // attach the file to the message MimeBodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null)); multipart.addBodyPart(attachmentBodyPart); // add the Multipart to the message msg.setContent(multipart); } if (from != null) { msg.setFrom(new InternetAddress(from, fromName)); } else { // There should be no way to get here logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); return true; } catch (SendFailedException e) { logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$ } catch (AuthenticationFailedException e) { logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$ } catch (Throwable e) { logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$ } return false; }
From source file:com.ctriposs.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 w w w.j ava 2 s . co m private static MimeMultipart createMultiPartEntity(ByteString entity, 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); 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.googlecode.ddom.saaj.SOAPMessageTest.java
@Validated @Test/* w w w . ja v a2s . com*/ public void testWriteToWithAttachment() throws Exception { SOAPMessage message = getFactory().createMessage(); message.getSOAPPart().getEnvelope().getBody().addBodyElement(new QName("urn:ns", "test", "p")); AttachmentPart attachment = message.createAttachmentPart(); attachment.setDataHandler(new DataHandler("This is a test", "text/plain; charset=iso-8859-15")); message.addAttachmentPart(attachment); ByteArrayOutputStream baos = new ByteArrayOutputStream(); message.writeTo(baos); System.out.write(baos.toByteArray()); MimeMultipart mp = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), "multipart/related")); assertEquals(2, mp.getCount()); BodyPart part1 = mp.getBodyPart(0); // TODO // assertEquals(messageSet.getVersion().getContentType(), part1.getContentType()); BodyPart part2 = mp.getBodyPart(1); // Note: text/plain is the default content type, so we need to include the parameters in the assertion assertEquals("text/plain; charset=iso-8859-15", part2.getContentType()); }
From source file:at.gv.egovernment.moa.id.configuration.helper.MailHelper.java
private static void sendMail(ConfigurationProvider config, String subject, String recipient, String content) throws ConfigurationException { try {/*from www. j a v a 2 s . c om*/ log.debug("Sending mail."); MiscUtil.assertNotNull(subject, "subject"); MiscUtil.assertNotNull(recipient, "recipient"); MiscUtil.assertNotNull(content, "content"); Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", config.getSMTPMailHost()); log.trace("Mail host: " + config.getSMTPMailHost()); if (config.getSMTPMailPort() != null) { log.trace("Mail port: " + config.getSMTPMailPort()); props.setProperty("mail.port", config.getSMTPMailPort()); } if (config.getSMTPMailUsername() != null) { log.trace("Mail user: " + config.getSMTPMailUsername()); props.setProperty("mail.user", config.getSMTPMailUsername()); } if (config.getSMTPMailPassword() != null) { log.trace("Mail password: " + config.getSMTPMailPassword()); props.setProperty("mail.password", config.getSMTPMailPassword()); } Session mailSession = Session.getDefaultInstance(props, null); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setSubject(subject); log.trace("Mail from: " + config.getMailFromName() + "/" + config.getMailFromAddress()); message.setFrom(new InternetAddress(config.getMailFromAddress(), config.getMailFromName())); log.trace("Recipient: " + recipient); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); log.trace("Creating multipart content of mail."); MimeMultipart multipart = new MimeMultipart("related"); log.trace("Adding first part (html)"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content, "text/html; charset=ISO-8859-15"); multipart.addBodyPart(messageBodyPart); // log.trace("Adding mail images"); // messageBodyPart = new MimeBodyPart(); // for (Image image : images) { // messageBodyPart.setDataHandler(new DataHandler(image)); // messageBodyPart.setHeader("Content-ID", "<" + image.getContentId() + ">"); // multipart.addBodyPart(messageBodyPart); // } message.setContent(multipart); transport.connect(); log.trace("Sending mail message."); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); log.trace("Successfully sent."); transport.close(); } catch (MessagingException e) { throw new ConfigurationException(e); } catch (UnsupportedEncodingException e) { throw new ConfigurationException(e); } }
From source file:org.exoplatform.extension.social.notifications.SocialNotificationService.java
/** * // w ww.j av a 2 s .c o m * @param invitedUsersList */ private void invitedUserNotification(Map<String, List<Space>> invitedUsersList) { for (Map.Entry<String, List<Space>> entry : invitedUsersList.entrySet()) { try { String userId = entry.getKey(); List<Space> spacesList = entry.getValue(); Locale locale = Locale.getDefault(); // get default locale of the manager String userLocale = this.getOrganizationService().getUserProfileHandler() .findUserProfileByName(userId).getAttribute("user.language"); Profile userProfile = getIdentityManager() .getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false).getProfile(); if (userLocale != null && !userLocale.trim().isEmpty()) { locale = new Locale(userLocale); } // getMessageTemplate MessageTemplate messageTemplate = this.getMailMessageTemplate( SocialNotificationConfiguration.MAIL_TEMPLATE_SPACE_PENDING_INVITATIONS, locale); GroovyTemplate g = new GroovyTemplate(messageTemplate.getSubject()); Map binding = new HashMap(); binding.put("userProfile", userProfile); binding.put("portalUrl", this.getPortalUrl()); binding.put("invitationUrl", this.getPortalUrl() + "/portal/intranet/invitationSpace"); binding.put("spacesList", spacesList); 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 invited user message.setRecipient(RecipientType.TO, new InternetAddress(userProfile.getEmail(), userProfile.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 : " + userProfile.getEmail() + " : " + subject + "\n" + html); mailService.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } } }