List of usage examples for javax.mail.internet MimeMultipart MimeMultipart
public MimeMultipart()
From source file:voldemort.coordinator.HttpGetAllRequestExecutor.java
public void writeResponseOld(Map<ByteArray, Versioned<byte[]>> responseVersioned) { // Multipart response MimeMultipart mp = new MimeMultipart(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {//from w w w . j a v a2 s . c om for (Entry<ByteArray, Versioned<byte[]>> entry : responseVersioned.entrySet()) { Versioned<byte[]> value = entry.getValue(); ByteArray keyByteArray = entry.getKey(); String base64Key = new String(Base64.encodeBase64(keyByteArray.get())); String contentLocationKey = "/" + this.storeName + "/" + base64Key; byte[] responseValue = value.getValue(); VectorClock vc = (VectorClock) value.getVersion(); VectorClockWrapper vcWrapper = new VectorClockWrapper(vc); ObjectMapper mapper = new ObjectMapper(); String eTag = ""; try { eTag = mapper.writeValueAsString(vcWrapper); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (logger.isDebugEnabled()) { logger.debug("ETAG : " + eTag); } // Create the individual body part MimeBodyPart body = new MimeBodyPart(); body.addHeader(CONTENT_TYPE, "application/octet-stream"); body.addHeader(CONTENT_LOCATION, contentLocationKey); body.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); body.addHeader(CONTENT_LENGTH, "" + responseValue.length); body.addHeader(ETAG, eTag); body.setContent(responseValue, "application/octet-stream"); mp.addBodyPart(body); } // At this point we have a complete multi-part response mp.writeTo(outputStream); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(outputStream.toByteArray()); // 1. Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // 2. Set the right headers response.setHeader(CONTENT_TYPE, "multipart/binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); // 3. Copy the data into the payload response.setContent(responseContent); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Update the stats if (this.coordinatorPerfStats != null) { long durationInNs = System.nanoTime() - startTimestampInNs; this.coordinatorPerfStats.recordTime(Tracked.GET_ALL, durationInNs); } // Write the response to the Netty Channel this.getRequestMessageEvent.getChannel().write(response); }
From source file:org.apache.lens.server.query.QueryEndNotifier.java
/** Send mail. * * @param host the host * @param port the port * @param email the email * @param mailSmtpTimeout the mail smtp timeout * @param mailSmtpConnectionTimeout the mail smtp connection timeout */ public static void sendMail(String host, String port, Email email, int mailSmtpTimeout, int mailSmtpConnectionTimeout) throws Exception { Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.timeout", mailSmtpTimeout); props.put("mail.smtp.connectiontimeout", mailSmtpConnectionTimeout); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(email.getFrom())); for (String recipient : email.getTo().trim().split("\\s*,\\s*")) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); }//from w ww. j a v a 2 s .co m if (email.getCc() != null && email.getCc().length() > 0) { for (String recipient : email.getCc().trim().split("\\s*,\\s*")) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(recipient)); } } message.setSubject(email.getSubject()); message.setSentDate(new Date()); MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setText(email.getMessage()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messagePart); message.setContent(multipart); Transport.send(message); }
From source file:mitm.common.mail.filter.UnsupportedFormatStripper.java
private MimeMessage buildMessage(MimeMessage source, PartsContext context) throws MessagingException, IOException { List<Part> parts = context.getParts(); assert (parts.size() > 0); MimeMessage newMessage;/* ww w . j a v a 2 s .c o m*/ if (parts.size() > 1) { /* there is more than one S/MIME part so we need to create a multipart message */ Multipart mp = new MimeMultipart(); for (Part part : parts) { MimeBodyPart bodyPart = BodyPartUtils.toMimeBodyPart(part); mp.addBodyPart(bodyPart); } newMessage = new MimeMessage(MailSession.getDefaultSession()); newMessage.setContent(mp); } else { newMessage = BodyPartUtils.toMessage(parts.get(0), true /* clone */); } copyNonContentHeaders(source, newMessage); return newMessage; }
From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java
private void addBody(MimeMessage msg) throws MessagingException { if (body != null) { Multipart multipart = new MimeMultipart(); BodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(body, contentType()); multipart.addBodyPart(bodyPart); msg.setContent(multipart);/*from w w w.j a va 2 s. c o m*/ } }
From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java
/** * Prepares message prior to be sent via execute()-method, i.e. sets * properties such as protocol, authentication, etc. * * @return Message-object to be sent to execute()-method * @throws MessagingException// w w w . j a v a 2s . c o m * when problems constructing or sending the mail occur * @throws IOException * when the mail content can not be read or truststore problems * are detected */ public Message prepareMessage() throws MessagingException, IOException { Properties props = new Properties(); String protocol = getProtocol(); // set properties using JAF props.setProperty("mail." + protocol + ".host", smtpServer); props.setProperty("mail." + protocol + ".port", getPort()); props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication)); // set timeout props.setProperty("mail." + protocol + ".timeout", getTimeout()); props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout()); if (useStartTLS || useSSL) { try { String allProtocols = StringUtils .join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " "); logger.info("Use ssl/tls protocols for mail: " + allProtocols); props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols); } catch (Exception e) { logger.error("Problem setting ssl/tls protocols for mail", e); } } if (enableDebug) { props.setProperty("mail.debug", "true"); } if (useStartTLS) { props.setProperty("mail.smtp.starttls.enable", "true"); if (enforceStartTLS) { // Requires JavaMail 1.4.2+ props.setProperty("mail.smtp.starttls.require", "true"); } } if (trustAllCerts) { if (useSSL) { props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY); props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false"); } else if (useStartTLS) { props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY); props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false"); } } else if (useLocalTrustStore) { File truststore = new File(trustStoreToUse); logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { logger.info( "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()); truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse); logger.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { logger.info( "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution."); throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath()); } } if (useSSL) { // Requires JavaMail 1.4.2+ props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore)); props.put("mail.smtps.ssl.socketFactory.fallback", "false"); } else if (useStartTLS) { // Requires JavaMail 1.4.2+ props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore)); props.put("mail.smtp.ssl.socketFactory.fallback", "false"); } } session = Session.getInstance(props, null); Message message; if (sendEmlMessage) { message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage))); } else { message = new MimeMessage(session); // handle body and attachments Multipart multipart = new MimeMultipart(); final int attachmentCount = attachments.size(); if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) { if (attachmentCount == 1) { // i.e. mailBody is empty File first = attachments.get(0); InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(first)); message.setText(IOUtils.toString(is)); } finally { IOUtils.closeQuietly(is); } } else { message.setText(mailBody); } } else { BodyPart body = new MimeBodyPart(); body.setText(mailBody); multipart.addBodyPart(body); for (File f : attachments) { BodyPart attach = new MimeBodyPart(); attach.setFileName(f.getName()); attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath()))); multipart.addBodyPart(attach); } message.setContent(multipart); } } // set from field and subject if (null != sender) { message.setFrom(new InternetAddress(sender)); } if (null != replyTo) { InternetAddress[] to = new InternetAddress[replyTo.size()]; message.setReplyTo(replyTo.toArray(to)); } if (null != subject) { message.setSubject(subject); } if (receiverTo != null) { InternetAddress[] to = new InternetAddress[receiverTo.size()]; receiverTo.toArray(to); message.setRecipients(Message.RecipientType.TO, to); } if (receiverCC != null) { InternetAddress[] cc = new InternetAddress[receiverCC.size()]; receiverCC.toArray(cc); message.setRecipients(Message.RecipientType.CC, cc); } if (receiverBCC != null) { InternetAddress[] bcc = new InternetAddress[receiverBCC.size()]; receiverBCC.toArray(bcc); message.setRecipients(Message.RecipientType.BCC, bcc); } for (int i = 0; i < headerFields.size(); i++) { Argument argument = (Argument) ((TestElementProperty) headerFields.get(i)).getObjectValue(); message.setHeader(argument.getName(), argument.getValue()); } message.saveChanges(); return message; }
From source file:bean.RedSocial.java
/** * /* w w w . j a v a 2 s . c om*/ * @param _username * @param _email * @param _password */ @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.ComentariosViaException.class) public void solicitarAcceso(String _username, String _email, String _password) { if (daoUsuario.obtenerUsuario(_username) != null) { throw new exceptionsBusiness.UsernameNoDisponible(); } String hash = BCrypt.hashpw(_password, BCrypt.gensalt()); Token token = new Token(_username, _email, hash); daoToken.guardarToken(token); //enviar token de acceso a la direccion email String correoEnvia = "skala2climbing@gmail.com"; String claveCorreo = "vNspLa5H"; // La configuracin para enviar correo Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); properties.put("mail.user", correoEnvia); properties.put("mail.password", claveCorreo); // Obtener la sesion Session session = Session.getInstance(properties, null); try { // Crear el cuerpo del mensaje MimeMessage mimeMessage = new MimeMessage(session); // Agregar quien enva el correo mimeMessage.setFrom(new InternetAddress(correoEnvia, "Skala2Climbing")); // Los destinatarios InternetAddress[] internetAddresses = { new InternetAddress(token.getEmail()) }; // Agregar los destinatarios al mensaje mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses); // Agregar el asunto al correo mimeMessage.setSubject("Confirmacin de registro"); // Creo la parte del mensaje MimeBodyPart mimeBodyPart = new MimeBodyPart(); String ip = "90.165.24.228"; mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: http://" + ip + ":8383/redsocialcolaborativaclientangularjs/confirmacion.html?" + "token=" + token.getToken()); //mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: "+"Enlace an no disponible"); // Crear el multipart para agregar la parte del mensaje anterior Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); // Agregar el multipart al cuerpo del mensaje mimeMessage.setContent(multipart); // Enviar el mensaje Transport transport = session.getTransport("smtp"); transport.connect(correoEnvia, claveCorreo); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (UnsupportedEncodingException | MessagingException ex) { throw new ErrorEnvioEmail(); } }
From source file:bo.com.offercruzmail.imp.InterpretadorMensajeGenerico.java
protected Multipart enviarPlantilla(boolean plantillaNueva, String idCargar) throws MessagingException, IOException { String nombreArchivoOrigen;//from w w w .j a v a 2 s .com String nombreAdjunto; List<T> lista = null; mensajesError = null; T entidad = null; getObjetoNegocio().setIdUsuario(idUsuario); getObjetoNegocio().setComandoPermiso(nombreEntidad); try { if (!plantillaNueva) { if ("todos".equals(idCargar)) { lista = getObjetoNegocio().obtenerTodos(); nombreArchivoOrigen = nombreEntidad + "-" + "lista"; nombreAdjunto = "lista_" + nombreEntidad + ".xlsx"; } else { ID id; try { id = convertirId(idCargar); } catch (Exception ex) { return FormadorMensajes.enviarIdCargarNoValido(); } entidad = getObjetoNegocio().recuperarPorId(id); if (entidad == null) { return FormadorMensajes.enviarEntidadNoExiste(idCargar); } nombreArchivoOrigen = nombreEntidad; nombreAdjunto = nombreEntidad + "_" + idCargar + ".xlsx"; } } else { nombreArchivoOrigen = nombreEntidad; nombreAdjunto = "plantilla_" + nombreEntidad + ".xlsx"; // if (this instanceof IInterpretadorFormularioDasometrico) { // if (cargarPlantillaFormularios) { // nombreArchivoOrigen = "plantillafrm"; // } // } } String nombreArchivoOriginal = "plantillas/" + nombreArchivoOrigen + ".xlsx"; File archivoCopia = UtilitariosMensajes.reservarNombre(nombreEntidad); UtilitariosMensajes.copiarArchivo(new File(nombreArchivoOriginal), archivoCopia); archivosTemporales.add(archivoCopia); FileInputStream fis = null; OutputStream os = null; try { Workbook libro; fis = new FileInputStream(archivoCopia); libro = WorkbookFactory.create(fis); hojaActual = new HojaExcelHelper(libro.getSheetAt(0)); if (plantillaNueva) { preparPlantillaAntesDeEnviar(libro); } else { if (lista != null) { mostrarLista(lista); } else { mostrarEntidad(entidad, libro); } } if (mensajesError != null) { return FormadorMensajes.enviarErroresNegocio(mensajesError); } //Guardamos cambio os = new FileOutputStream(archivoCopia); libro.write(os); } catch (InvalidFormatException ex) { } finally { if (fis != null) { fis.close(); } if (os != null) { os.close(); } } String textoMensaje; if (plantillaNueva) { textoMensaje = escapeHtml4("La plantilla est adjunta a este mensaje."); } else if (lista != null) { textoMensaje = "La consulta ha devuelto " + lista.size() + " registro(s)."; } else { textoMensaje = escapeHtml4("El registro solicitado est adjunto a este mensaje"); } Multipart cuerpo = new MimeMultipart(); BodyPart adjunto = new MimeBodyPart(); DataSource origen = new FileDataSource(archivoCopia); adjunto.setDataHandler(new DataHandler(origen)); adjunto.setFileName(nombreAdjunto); cuerpo.addBodyPart(FormadorMensajes.getBodyPartEnvuelto(textoMensaje)); cuerpo.addBodyPart(adjunto); return cuerpo; } catch (PermisosInsuficientesException ex) { appendException(new BusinessExceptionMessage(ex.getMessage(), "Autentificacion")); } if (mensajesError != null) { return FormadorMensajes.enviarErroresNegocio(mensajesError); } return null; }
From source file:com.adaptris.util.text.mime.MultiPartOutput.java
private void writeViaTempfile(OutputStream out, File tempFile) throws MessagingException, IOException { try (FileOutputStream fileOut = new FileOutputStream(tempFile); CountingOutputStream counter = new CountingOutputStream(fileOut)) { MimeMultipart multipart = new MimeMultipart(); mimeHeader.setHeader(HEADER_CONTENT_TYPE, multipart.getContentType()); // Write the part out to the stream first. for (KeyedBodyPart kbp : parts) { multipart.addBodyPart(kbp.getData()); }/*from w w w . j a va 2 s . co m*/ multipart.writeTo(counter); counter.flush(); mimeHeader.setHeader(HEADER_CONTENT_LENGTH, String.valueOf(counter.count())); } writeHeaders(mimeHeader, out); try (InputStream in = new FileInputStream(tempFile)) { IOUtils.copy(in, out); } }
From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java
public static void SendEmailAnda(String from, String to1, String subject, String filename) throws FileNotFoundException, IOException { //Get properties object Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); //get Session Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, "anda.cristea"); }//ww w. j a v a 2 s. c om }); //compose message try { MimeMessage message = new MimeMessage(session); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to1)); message.setSubject(subject); // message.setText(msg); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Raport teste automate"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); //message.setContent(multipart); StringWriter writer = new StringWriter(); IOUtils.copy(new FileInputStream(new File(filename)), writer); message.setContent(writer.toString(), "text/html"); //send message Transport.send(message); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:fsi_admin.JSmtpConn.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ERROR = null, codErr = null; try {//from ww w . ja v a 2 s. co m Properties parametros = new Properties(); Vector archivos = new Vector(); DiskFileUpload fu = new DiskFileUpload(); List items = fu.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) parametros.put(item.getFieldName(), item.getString()); else archivos.addElement(item); } if (parametros.getProperty("SERVER") == null || parametros.getProperty("DATABASE") == null || parametros.getProperty("USER") == null || parametros.getProperty("PASSWORD") == null || parametros.getProperty("BODY") == null || parametros.getProperty("MIMETYPE") == null || parametros.getProperty("SUBJECT") == null || parametros.getProperty("EMAIL") == null || parametros.getProperty("SOURCEMAIL") == null) { System.out.println("No recibi parametros de conexin antes del correo a enviar"); ERROR = "ERROR: El servidor no recibi todos los parametros de conexion (SERVER,DATABASE,USER,PASSWORD) antes del correo a enviar"; codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 3); } //Hasta aqui se han enviado todos los parametros ninguno nulo if (ERROR == null) { StringBuffer msj = new StringBuffer(), SMTPHOST = new StringBuffer(), SMTPPORT = new StringBuffer(), SMTPUSR = new StringBuffer(), SMTPPASS = new StringBuffer(); MutableBoolean COBRAR = new MutableBoolean(false); MutableDouble COSTO = new MutableDouble(0.0), SALDO = new MutableDouble(0.0); // Primero obtiene info del SMTP if (!obtenInfoSMTP(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), SMTPHOST, SMTPPORT, SMTPUSR, SMTPPASS, msj, COSTO, SALDO, COBRAR)) { System.out.println("El usuario y contrasea de servicio estan mal"); ERROR = msj.toString(); codErr = "2"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 2); } else { if (COBRAR.booleanValue() && SALDO.doubleValue() < COSTO.doubleValue()) { System.out.println("El servicio tiene un costo que no alcanza en el saldo"); ERROR = "El servicio SMTP tiene un costo que no alcanza en el saldo"; codErr = "2"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 2); } else { Properties props; props = System.getProperties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.port", Integer.parseInt(SMTPPORT.toString())); // Set properties indicating that we want to use STARTTLS to encrypt the connection. // The SMTP session will begin on an unencrypted connection, and then the client // will issue a STARTTLS command to upgrade to an encrypted connection. props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.starttls.required", "true"); // Create a Session object to represent a mail session with the specified properties. Session session = Session.getDefaultInstance(props); MimeMessage mmsg = new MimeMessage(session); BodyPart messagebodypart = new MimeBodyPart(); MimeMultipart multipart = new MimeMultipart(); if (!prepareMsg(parametros.getProperty("SOURCEMAIL"), parametros.getProperty("EMAIL"), parametros.getProperty("SUBJECT"), parametros.getProperty("MIMETYPE"), parametros.getProperty("BODY"), msj, props, session, mmsg, messagebodypart, multipart)) { System.out.println("No se permiti preparar el mensaje"); ERROR = msj.toString(); codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 3); } else { if (!adjuntarArchivo(msj, messagebodypart, multipart, archivos)) { System.out.println("No se permiti adjuntar archivos al mensaje"); ERROR = msj.toString(); codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 3); } else { if (!sendMsg(SMTPHOST.toString(), SMTPUSR.toString(), SMTPPASS.toString(), msj, session, mmsg, multipart)) { System.out.println("No se permiti enviar el mensaje"); ERROR = msj.toString(); codErr = "3"; ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(), parametros.getProperty("SERVER"), parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), request, ERROR, 3); } else { ingresarRegistroExitoso(parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"), parametros.getProperty("SUBJECT"), COSTO, SALDO, COBRAR); //Devuelve la respuesta al cliente Element Correo = new Element("Correo"); Correo.setAttribute("Subject", parametros.getProperty("SUBJECT")); Correo.setAttribute("MsjError", ""); Document Reporte = new Document(Correo); Format format = Format.getPrettyFormat(); format.setEncoding("utf-8"); format.setTextMode(TextMode.NORMALIZE); XMLOutputter xmlOutputter = new XMLOutputter(format); ByteArrayOutputStream out = new ByteArrayOutputStream(); xmlOutputter.output(Reporte, out); byte[] data = out.toByteArray(); ByteArrayInputStream istream = new ByteArrayInputStream(data); String destino = "Correo.xml"; JBajarArchivo fd = new JBajarArchivo(); fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length, destino); } } } } } } } catch (Exception e) { e.printStackTrace(); ERROR = "ERROR DE EXCEPCION EN SERVIDOR PAC: " + e.getMessage(); } //Genera el archivo XML de error para ser devuelto al Servidor if (ERROR != null) { Element SIGN_ERROR = new Element("SIGN_ERROR"); SIGN_ERROR.setAttribute("CodError", codErr); SIGN_ERROR.setAttribute("MsjError", ERROR); Document Reporte = new Document(SIGN_ERROR); Format format = Format.getPrettyFormat(); format.setEncoding("utf-8"); format.setTextMode(TextMode.NORMALIZE); XMLOutputter xmlOutputter = new XMLOutputter(format); ByteArrayOutputStream out = new ByteArrayOutputStream(); xmlOutputter.output(Reporte, out); byte[] data = out.toByteArray(); ByteArrayInputStream istream = new ByteArrayInputStream(data); String destino = "SIGN_ERROR.xml"; JBajarArchivo fd = new JBajarArchivo(); fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length, destino); } }