List of usage examples for javax.mail.internet MimeMultipart MimeMultipart
public MimeMultipart()
From source file:org.openmeetings.test.calendar.TestSendIcalMessage.java
private void sendIcalMessage() throws Exception { log.debug("sendIcalMessage"); // Evaluating Configuration Data String smtpServer = cfgManagement.getConfKey(3, "smtp_server").getConf_value(); String smtpPort = cfgManagement.getConfKey(3, "smtp_port").getConf_value(); // String from = "openmeetings@xmlcrm.org"; String from = cfgManagement.getConfKey(3, "system_email_addr").getConf_value(); String emailUsername = cfgManagement.getConfKey(3, "email_username").getConf_value(); String emailUserpass = cfgManagement.getConfKey(3, "email_userpass").getConf_value(); Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); props.put("mail.smtp.port", smtpPort); Configuration conf = cfgManagement.getConfKey(3, "mail.smtp.starttls.enable"); if (conf != null) { if (conf.getConf_value().equals("1")) { props.put("mail.smtp.starttls.enable", "true"); }/* w w w .j a v a2 s . co m*/ } // Check for Authentification Session session = null; if (emailUsername != null && emailUsername.length() > 0 && emailUserpass != null && emailUserpass.length() > 0) { // use SMTP Authentication props.put("mail.smtp.auth", "true"); session = Session.getDefaultInstance(props, new SmtpAuthenticator(emailUsername, emailUserpass)); } else { // not use SMTP Authentication session = Session.getDefaultInstance(props, null); } // Building MimeMessage MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject(subject); mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients, false)); // -- Create a new message -- BodyPart msg = new MimeBodyPart(); msg.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlBody, "text/html; charset=\"utf-8\""))); Multipart multipart = new MimeMultipart(); BodyPart iCalAttachment = new MimeBodyPart(); iCalAttachment.setDataHandler(new DataHandler(new javax.mail.util.ByteArrayDataSource( new ByteArrayInputStream(iCalMimeBody), "text/calendar;method=REQUEST;charset=\"UTF-8\""))); iCalAttachment.setFileName("invite.ics"); multipart.addBodyPart(iCalAttachment); multipart.addBodyPart(msg); mimeMessage.setSentDate(new Date()); mimeMessage.setContent(multipart); // -- Set some other header information -- // mimeMessage.setHeader("X-Mailer", "XML-Mail"); // mimeMessage.setSentDate(new Date()); // Transport trans = session.getTransport("smtp"); Transport.send(mimeMessage); }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java
public boolean dispatch(BIObject document, byte[] executionOutput) { String contentType;//from w w w . ja v a 2 s . c om String fileExtension; String nameSuffix; JobExecutionContext jobExecutionContext; logger.debug("IN"); try { contentType = dispatchContext.getContentType(); fileExtension = dispatchContext.getFileExtension(); nameSuffix = dispatchContext.getNameSuffix(); jobExecutionContext = dispatchContext.getJobExecutionContext(); //Custom Trusted Store Certificate Options String trustedStorePath = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.file"); String trustedStorePassword = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.password"); String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl); if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; int smptPort = 25; if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); /* if( (user==null) || user.trim().equals("")) throw new Exception("Smtp user not configured"); if( (pass==null) || pass.trim().equals("")) throw new Exception("Smtp password not configured"); */ String mailTos = ""; List dlIds = dispatchContext.getDlIds(); Iterator it = dlIds.iterator(); while (it.hasNext()) { Integer dlId = (Integer) it.next(); DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId); List emails = new ArrayList(); emails = dl.getEmails(); Iterator j = emails.iterator(); while (j.hasNext()) { Email e = (Email) j.next(); String email = e.getEmail(); String userTemp = e.getUserId(); IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp); if (ObjectsAccessVerifier.canSee(document, userProfile)) { if (j.hasNext()) { mailTos = mailTos + email + ","; } else { mailTos = mailTos + email; } } } } if ((mailTos == null) || mailTos.trim().equals("")) { throw new Exception("No recipient address found"); } String[] recipients = mailTos.split(","); //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", Integer.toString(smptPort)); Session session = null; if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) { props.put("mail.smtp.auth", "false"); session = Session.getInstance(props); logger.debug("Connecting to mail server without authentication"); } else { props.put("mail.smtp.auth", "true"); Authenticator auth = new SMTPAuthenticator(user, pass); //SSL Connection if (smtpssl.equals("true")) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //props.put("mail.smtp.debug", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort)); if ((!StringUtilities.isEmpty(trustedStorePath))) { /* Dynamic configuration of trustedstore for CA * Using Custom SSLSocketFactory to inject certificates directly from specified files */ //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY); } else { //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY); } props.put("mail.smtp.socketFactory.fallback", "false"); } session = Session.getInstance(props, auth); logger.debug("Connecting to mail server with authentication"); } // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder(); String subject = document.getName() + nameSuffix; msg.setSubject(subject); // create and fill the first message part //MimeBodyPart mbp1 = new MimeBodyPart(); //mbp1.setText(mailTxt); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType, document.getName() + nameSuffix + fileExtension); mbp2.setDataHandler(new DataHandler(sds)); mbp2.setFileName(sds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); //mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smptPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { //Use normal SMTP Transport.send(msg); } if (jobExecutionContext.getNextFireTime() == null) { String triggername = jobExecutionContext.getTrigger().getName(); dlIds = dispatchContext.getDlIds(); it = dlIds.iterator(); while (it.hasNext()) { Integer dlId = (Integer) it.next(); DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId); DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl, (document.getId()).intValue(), triggername); } } } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:com.szmslab.quickjavamail.send.MailSender.java
/** * MimeMultipart????mulpart/mixed * * @return MimeMultipartmulpart/mixed? */ private MimeMultipart createMixedMimeMultipart() { return new MimeMultipart(); }
From source file:com.waveerp.sendMail.java
public String sendMsgWithAttach(String strSource, String strSourceDesc, String strSubject, String strMsg, String strDestination, String strDestDesc, String strPath) throws Exception { String strResult = "OK"; // Call the registry management system registrySystem rs = new registrySystem(); // Call the encryption management system desEncryption de = new desEncryption(); de.Encrypter("", ""); String strHost = rs.readRegistry("NA", "NA", "NA", "EMAILHOST"); String strPort = rs.readRegistry("NA", "NA", "NA", "EMAILPORT"); final String strUser = rs.readRegistry("NA", "NA", "NA", "EMAILUSER"); String strPass = rs.readRegistry("NA", "NA", "NA", "EMAILPASSWORD"); //Decrypt the encrypted password. final String strPass01 = de.decrypt(strPass); Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", strHost); props.put("mail.smtp.port", strPort); props.put("mail.user", strUser); props.put("mail.password", strPass01); // creates a new session with an authenticator Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(strUser, strPass01); }//from w w w .j ava2 s . c o m }; Session session = Session.getInstance(props, auth); // creates a new e-mail message Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(strSource)); //InternetAddress[] toAddresses = { new InternetAddress(strDestination) }; msg.setRecipient(Message.RecipientType.TO, new InternetAddress(strDestination)); msg.setSubject(strSubject); msg.setSentDate(new Date()); // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(strMsg, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // adds attachments //if (attachFiles != null && attachFiles.length > 0) { // for (String filePath : attachFiles) { // MimeBodyPart attachPart = new MimeBodyPart(); // // try { // attachPart.attachFile(filePath); // } catch (IOException ex) { // ex.printStackTrace(); // } // // multipart.addBodyPart(attachPart); // } //} String fna; String fnb; URL fileUrl; fileUrl = null; fileUrl = this.getClass().getResource("sendMail.class"); fna = fileUrl.getPath(); fna = fna.substring(0, fna.indexOf("WEB-INF")); //fnb = URLDecoder.decode( fna + TEMP_DIR + strPath ); fnb = URLDecoder.decode(fna + strPath); MimeBodyPart attachPart = new MimeBodyPart(); try { attachPart.attachFile(fnb); } catch (IOException ex) { //ex.printStackTrace(); strResult = ex.getMessage(); } multipart.addBodyPart(attachPart); // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); return strResult; }
From source file:org.silverpeas.core.mail.TestSmtpMailSending.java
@Test public void sendingMailSynchronouslyWithFromWithToPersonalWithSubjectWithMultipartContentAndDefaultValues() throws Exception { MailAddress senderEmail = MailAddress.eMail(COMMON_FROM); 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);/* w w w .ja v a 2 s. c om*/ MailSending mailSending = MailSending.from(senderEmail).to(receiverEmail).withSubject(subject) .withContent(content); // 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(false)); assertThat(mailToSend.isAsynchronous(), is(false)); assertMailSent(mailToSend); }
From source file:gmailclientfx.core.GmailClient.java
public static void sendMessage(String to, String subject, String body, List<String> attachments) throws Exception { // authenticate with gmail smtp server SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, EMAIL, ACCESS_TOKEN, true); // kreiraj MimeMessage objekt MimeMessage msg = new MimeMessage(OAuth2Authenticator.getSession()); // dodaj headere msg.addHeader("Content-type", "text/HTML; charset=UTF-8"); msg.addHeader("format", "flowed"); msg.addHeader("Content-Transfer-Encoding", "8bit"); msg.setFrom(new InternetAddress(EMAIL)); msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(to)); msg.setSubject(subject, "UTF-8"); msg.setReplyTo(InternetAddress.parse(EMAIL, false)); // tijelo poruke BodyPart msgBodyPart = new MimeBodyPart(); msgBodyPart.setText(body);//from ww w .ja v a 2s. c o m Multipart multipart = new MimeMultipart(); multipart.addBodyPart(msgBodyPart); msg.setContent(multipart); // dodaj privitke if (attachments.size() > 0) { for (String attachment : attachments) { msgBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); msgBodyPart.setDataHandler(new DataHandler(source)); msgBodyPart.setFileName(source.getName()); multipart.addBodyPart(msgBodyPart); } msg.setContent(multipart); } smtpTransport.sendMessage(msg, InternetAddress.parse(to)); Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Poruka poslana!"); alert.setHeaderText(null); alert.setContentText("Email uspjeno poslan!"); alert.showAndWait(); }
From source file:com.eviware.soapui.impl.support.AbstractMockResponse.java
public String writeResponse(MockResult result, String responseContent) throws Exception { MimeMultipart mp = null;// w w w . j a v a 2 s.c om Operation operation = getMockOperation().getOperation(); // variables needed for both multipart sections.... boolean isXOP = isMtomEnabled() && isForceMtom(); StringToStringMap contentIds = new StringToStringMap(); // only support multipart for wsdl currently..... if (operation instanceof WsdlOperation) { if (operation == null) { throw new IllegalStateException("Missing WsdlOperation for mock response"); } // preprocess only if neccessary if (isMtomEnabled() || isInlineFilesEnabled() || getAttachmentCount() > 0) { try { mp = new MimeMultipart(); WsdlOperation wsdlOperation = ((WsdlOperation) operation); MessageXmlObject requestXmlObject = createMessageXmlObject(responseContent, wsdlOperation); MessageXmlPart[] requestParts = requestXmlObject.getMessageParts(); for (MessageXmlPart requestPart : requestParts) { if (prepareMessagePart(mp, contentIds, requestPart)) { isXOP = true; } } responseContent = requestXmlObject.getMessageContent(); } catch (Exception e) { SoapUI.logError(e); } } responseContent = removeEmptyContent(responseContent); } if (isStripWhitespaces()) { responseContent = XmlUtils.stripWhitespaces(responseContent); } MockRequest request = result.getMockRequest(); request.getHttpResponse().setStatus(this.getResponseHttpStatus()); ByteArrayOutputStream outData = new ByteArrayOutputStream(); // non-multipart request? String responseCompression = getResponseCompression(); if (!isXOP && (mp == null || mp.getCount() == 0) && getAttachmentCount() == 0) { String encoding = getEncoding(); if (responseContent == null) { responseContent = ""; } byte[] content = encoding == null ? responseContent.getBytes() : responseContent.getBytes(encoding); if (!result.getResponseHeaders().containsKeyIgnoreCase("Content-Type")) { result.setContentType(getContentType()); } String acceptEncoding = result.getMockRequest().getRequestHeaders().get("Accept-Encoding", ""); if (AUTO_RESPONSE_COMPRESSION.equals(responseCompression) && acceptEncoding != null && acceptEncoding.toUpperCase().contains("GZIP")) { if (!headerExists("Content-Encoding", "gzip", result)) { result.addHeader("Content-Encoding", "gzip"); } outData.write(CompressionSupport.compress(CompressionSupport.ALG_GZIP, content)); } else if (AUTO_RESPONSE_COMPRESSION.equals(responseCompression) && acceptEncoding != null && acceptEncoding.toUpperCase().contains("DEFLATE")) { result.addHeader("Content-Encoding", "deflate"); outData.write(CompressionSupport.compress(CompressionSupport.ALG_DEFLATE, content)); } else { outData.write(content); } } else // won't get here if rest at the moment... { // make sure.. if (mp == null) { mp = new MimeMultipart(); } // init root part initRootPart(responseContent, mp, isXOP); // init mimeparts AttachmentUtils.addMimeParts(this, Arrays.asList(getAttachments()), mp, contentIds); // create request message MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION); message.setContent(mp); message.saveChanges(); MimeMessageMockResponseEntity mimeMessageRequestEntity = new MimeMessageMockResponseEntity(message, isXOP, this); result.addHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue()); result.addHeader("MIME-Version", "1.0"); mimeMessageRequestEntity.writeTo(outData); } if (outData.size() > 0) { byte[] data = outData.toByteArray(); if (responseCompression.equals(CompressionSupport.ALG_DEFLATE) || responseCompression.equals(CompressionSupport.ALG_GZIP)) { result.addHeader("Content-Encoding", responseCompression); data = CompressionSupport.compress(responseCompression, data); } if (result.getResponseHeaders().get("Transfer-Encoding") == null) { result.addHeader("Content-Length", "" + data.length); } result.writeRawResponseData(data); } return responseContent; }
From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java
/** * Fill the body of a message already created. * The result message depends on the information given. * /*from w ww. ja v a 2 s . c om*/ * @param message * @param text * @param html * @param parts * @return The composed message * @throws MessagingException * @throws IOException */ @SuppressWarnings("rawtypes") public static Message composeMessage(Message message, String text, String html, List parts) throws MessagingException, IOException { MimeBodyPart txtPart = null; MimeBodyPart htmlPart = null; MimeMultipart mimeMultipart = null; if (text == null && html == null) { text = ""; } if (text != null) { txtPart = new MimeBodyPart(); txtPart.setContent(text, "text/plain"); } if (html != null) { htmlPart = new MimeBodyPart(); htmlPart.setContent(html, "text/html"); } if (html != null && text != null) { mimeMultipart = new MimeMultipart(); mimeMultipart.setSubType("alternative"); mimeMultipart.addBodyPart(txtPart); mimeMultipart.addBodyPart(htmlPart); } if (parts == null || parts.isEmpty()) { if (mimeMultipart != null) { message.setContent(mimeMultipart); } else if (html != null) { message.setText(html); message.setHeader("Content-type", "text/html"); } else if (text != null) { message.setText(text); } } else { MimeBodyPart bodyPart = new MimeBodyPart(); if (mimeMultipart != null) { bodyPart.setContent(mimeMultipart); } else if (html != null) { bodyPart.setText(html); bodyPart.setHeader("Content-type", "text/html"); } else if (text != null) { bodyPart.setText(text); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); for (Object attachment : parts) { if (attachment instanceof FileItem) { multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment)); } else { multipart.addBodyPart((BodyPart) attachment); } } message.setContent(multipart); } message.saveChanges(); return message; }
From source file:gov.nih.nci.cacis.nav.AbstractSendMail.java
/** * Creates MimeMessage with supplied values * //from w w w. j a v a2 s . co 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.googlecode.gmail4j.javamail.JavaMailGmailMessage.java
@Override public void addAttachement(File file) { try {/*from ww w . ja v a 2 s . co m*/ /* Check if email has already some contents. */ Object content; try { content = this.source.getContent(); } catch (IOException e) { /* If no content, then content is null.*/ content = null; log.warn("Email content is empty.", e); } if (content != null) { if (content instanceof String) { /* This message is not multipart yet. Change it to multipart. */ MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText((String) this.source.getContent()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); this.source.setContent(multipart); } } else { /* No content, then create initial multipart content. */ Multipart multipart = new MimeMultipart(); this.source.setContent(multipart); } /* Get current content. */ Multipart multipart = (Multipart) this.source.getContent(); /* add attachment as a new part. */ MimeBodyPart attachementPart = new MimeBodyPart(); DataSource fileSource = new FileDataSource(file); DataHandler fileDataHandler = new DataHandler(fileSource); attachementPart.setDataHandler(fileDataHandler); attachementPart.setFileName(file.getName()); multipart.addBodyPart(attachementPart); } catch (Exception e) { throw new GmailException("Failed to add attachement", e); } }