List of usage examples for javax.mail Transport send
public static void send(Message msg) throws MessagingException
From source file:org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java
public static void sendMail(Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if (ArgList.length == 5) { try {/*from ww w . ja va2 s. com*/ // Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", ArgList[0]); // create some properties and get the default Session Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress((String) ArgList[1]); msg.setFrom(addressFrom); // Get Recipients String[] strArrRecipients = ((String) ArgList[2]).split(","); InternetAddress[] addressTo = new InternetAddress[strArrRecipients.length]; for (int i = 0; i < strArrRecipients.length; i++) { addressTo[i] = new InternetAddress(strArrRecipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject((String) ArgList[3]); msg.setContent(ArgList[4], "text/plain"); Transport.send(msg); } catch (Exception e) { throw Context.reportRuntimeError("sendMail: " + e.toString()); } } else { throw Context.reportRuntimeError("The function call sendMail requires 5 arguments."); } }
From source file:com.photon.phresco.util.Utility.java
public static void sendNewPassword(String[] toAddr, String fromAddr, String user, String subject, String body, String username, String password, String host, String screen, String build) throws PhrescoException { List<String> lists = Arrays.asList(toAddr); if (fromAddr == null) { fromAddr = "phresco.do.not.reply@gmail.com"; username = "phresco.do.not.reply@gmail.com"; password = "phresco123"; }/* ww w . j a v a 2 s . c o m*/ Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getDefaultInstance(props, new LoginAuthenticator(username, password)); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddr)); List<Address> emailsList = getEmailsList(lists); Address[] dsf = new Address[emailsList.size()]; message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf)); message.setSubject(subject); message.setContent(body, "text/html"); Transport.send(message); } catch (MessagingException e) { throw new PhrescoException(e); } }
From source file:GUI.DashbordAdminFrame.java
private void btnEnvMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnvMailActionPerformed // TODO add your handling code here: String to = null;/*from w w w.ja va 2s .co m*/ UserDao u = new UserDao(); List listeTo = new ArrayList(); listeTo = u.findAllEmail(); String from = "allfordealpi@gmail.com"; final String username = "allfordealpi@gmail.com"; final String password = "pidev2016"; String host = "smtp.gmail.com"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "587"); // Get the Session object. Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); for (Object o : listeTo) { to = (String) o; System.out.println(to); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(tfObjet.getText()); message.setText(taContenu.getText()); // Send message Transport.send(message); } System.out.println("Sent message successfully...."); } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java
private void sendToDl(DispatchContext sInfo, BIObject biobj, byte[] response, String retCT, String fileExt, String toBeAppendedToName, String toBeAppendedToDescription) { logger.debug("IN"); try {//from ww w . j av a 2 s. c om String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); 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"; String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) throw new Exception("Smtp user not configured"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) throw new Exception("Smtp password not configured"); String mailTos = ""; List dlIds = sInfo.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(biobj, 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.auth", "true"); // create autheticator object Authenticator auth = new SMTPAuthenticator(user, pass); // open session Session session = Session.getDefaultInstance(props, auth); // 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 = biobj.getName() + toBeAppendedToName; 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(response, retCT, biobj.getName() + toBeAppendedToName + fileExt); 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 Transport.send(msg); } catch (Exception e) { logger.error("Error while sending schedule result mail", e); } finally { logger.debug("OUT"); } }
From source file:com.github.dougkelly88.FLIMPlateReaderGUI.SequencingClasses.GUIComponents.XYSequencing.java
public void sendEmail(String subject, String text, String toEmail) { // Recipient's email ID needs to be mentioned. String to = toEmail;// w ww . j av a2s . c o m // Sender's email ID needs to be mentioned String from = "flimplatereader@gmail.com"; // Assuming you are sending email from localhost String host = "localhost"; // Get system properties // Properties properties = System.getProperties(); Properties properties = System.getProperties(); // Setup mail server //properties.setProperty("mail.smtp.host", "10.101.3.229"); properties.setProperty("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); properties.setProperty("mail.user", "flimplatereader"); properties.setProperty("mail.password", "flimimages"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.auth", "true"); //enable authentication final String pww = "flimimages"; Session session; session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication("flimplatereader@gmail.com", pww); } }); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject(subject); // Now set the actual message message.setText(text); // Send message Transport.send(message); System.out.println("Sent message successfully...."); } catch (MessagingException mex) { mex.printStackTrace(); } }
From source file:org.olat.core.util.mail.manager.MailManagerImpl.java
@Override public void sendMessage(MimeMessage msg, MailerResult result) { try {//from w w w. j a va2s.c om if (Settings.isJUnitTest()) { //we want not send really e-mails } else if (mailModule.isMailHostEnabled() && result.getReturnCode() == MailerResult.OK) { // now send the mail if (Settings.isDebuging()) { try { logInfo("E-mail send: " + msg.getSubject()); logInfo("Content : " + msg.getContent()); } catch (IOException e) { logError("", e); } } Transport.send(msg); } else if (Settings.isDebuging() && result.getReturnCode() == MailerResult.OK) { try { logInfo("E-mail send: " + msg.getSubject()); logInfo("Content : " + msg.getContent()); } catch (IOException e) { logError("", e); } } else { result.setReturnCode(MailerResult.MAILHOST_UNDEFINED); } } catch (MessagingException e) { result.setReturnCode(MailerResult.SEND_GENERAL_ERROR); logWarn("Could not send mail", e); } }
From source file:com.tremolosecurity.provisioning.core.ProvisioningEngineImpl.java
private void sendEmail(SmtpMessage msg) throws MessagingException { Properties props = new Properties(); boolean doAuth = false; props.setProperty("mail.smtp.host", prov.getSmtpHost()); props.setProperty("mail.smtp.port", Integer.toString(prov.getSmtpPort())); if (prov.getSmtpUser() != null && !prov.getSmtpUser().isEmpty()) { logger.debug("SMTP user found '" + prov.getSmtpUser() + "', enabling authentication"); props.setProperty("mail.smtp.user", prov.getSmtpUser()); props.setProperty("mail.smtp.auth", "true"); doAuth = true;/* www . j av a 2 s .c om*/ } else { logger.debug("No SMTP user, disabling authentication"); doAuth = false; props.setProperty("mail.smtp.auth", "false"); } props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.smtp.starttls.enable", Boolean.toString(prov.isSmtpTLS())); if (logger.isDebugEnabled()) { props.setProperty("mail.debug", "true"); props.setProperty("mail.socket.debug", "true"); } if (prov.getLocalhost() != null && !prov.getLocalhost().isEmpty()) { props.setProperty("mail.smtp.localhost", prov.getLocalhost()); } if (prov.isUseSOCKSProxy()) { props.setProperty("mail.smtp.socks.host", prov.getSocksProxyHost()); props.setProperty("mail.smtp.socks.port", Integer.toString(prov.getSocksProxyPort())); props.setProperty("mail.smtps.socks.host", prov.getSocksProxyHost()); props.setProperty("mail.smtps.socks.port", Integer.toString(prov.getSocksProxyPort())); } //Session session = Session.getInstance(props, new SmtpAuthenticator(this.smtpUser,this.smtpPassword)); Session session = null; if (doAuth) { logger.debug("Creating authenticated session"); session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(prov.getSmtpUser(), prov.getSmtpPassword()); } }); } else { logger.debug("Creating unauthenticated session"); session = Session.getInstance(props); } if (logger.isDebugEnabled()) { session.setDebugOut(System.out); session.setDebug(true); } //Transport tr = session.getTransport("smtp"); //tr.connect(); //tr.connect(this.smtpHost,this.smtpPort, this.smtpUser, this.smtpPassword); Message msgToSend = new MimeMessage(session); msgToSend.setFrom(new InternetAddress(msg.from)); msgToSend.addRecipient(Message.RecipientType.TO, new InternetAddress(msg.to)); msgToSend.setSubject(msg.subject); if (msg.contentType != null) { msgToSend.setContent(msg.msg, msg.contentType); } else { msgToSend.setText(msg.msg); } msgToSend.saveChanges(); Transport.send(msgToSend); //tr.sendMessage(msg, msg.getAllRecipients()); //tr.close(); }
From source file:org.bimserver.webservices.Service.java
@Override public void sendCompareEmail(SCompareType sCompareType, SCompareIdentifier sCompareIdentifier, Long poid, Long roid1, Long roid2, String address) throws ServerException, UserException { DatabaseSession session = bimServer.getDatabase().createSession(); try {/*from www. ja v a2 s .co m*/ SUser currentUser = getCurrentUser(session); Revision revision1 = session.get(StorePackage.eINSTANCE.getRevision(), roid1, false, null); Revision revision2 = session.get(StorePackage.eINSTANCE.getRevision(), roid2, false, null); String senderName = currentUser.getName(); String senderAddress = currentUser.getUsername(); if (!senderAddress.contains("@") || !senderAddress.contains(".")) { senderAddress = bimServer.getSettingsManager().getSettings().getEmailSenderAddress(); } Session mailSession = bimServer.getMailSystem().createMailSession(); Message msg = new MimeMessage(mailSession); try { InternetAddress addressFrom = new InternetAddress(senderAddress); addressFrom.setPersonal(senderName); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[1]; addressTo[0] = new InternetAddress(address); msg.setRecipients(Message.RecipientType.TO, addressTo); msg.setSubject("BIMserver Model Comparator"); SCompareResult compareResult = compare(roid1, roid2, sCompareType, sCompareIdentifier); String html = CompareWriter.writeCompareResult(compareResult, revision1.getId(), revision2.getId(), sCompareType, getProjectByPoid(poid), false); msg.setContent(html, "text/html"); Transport.send(msg); } catch (AddressException e) { throw new UserException(e); } catch (UnsupportedEncodingException e) { throw new UserException(e); } catch (MessagingException e) { throw new UserException(e); } } finally { session.close(); } }
From source file:org.kuali.test.utils.Utils.java
/** * //from w ww.jav a2 s . c o m * @param configuration * @param overrideEmail * @param testSuite * @param testHeader * @param testResults * @param errorCount * @param warningCount * @param successCount */ public static void sendMail(KualiTestConfigurationDocument.KualiTestConfiguration configuration, String overrideEmail, TestSuite testSuite, TestHeader testHeader, List<File> testResults, int errorCount, int warningCount, int successCount) { if (StringUtils.isNotBlank(configuration.getEmailSetup().getFromAddress()) && StringUtils.isNotBlank(configuration.getEmailSetup().getMailHost())) { String[] toAddresses = getEmailToAddresses(configuration, testSuite, testHeader); if (toAddresses.length > 0) { Properties props = new Properties(); props.put("mail.smtp.host", configuration.getEmailSetup().getMailHost()); Session session = Session.getDefaultInstance(props, null); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(configuration.getEmailSetup().getFromAddress())); if (StringUtils.isBlank(overrideEmail)) { for (String recipient : toAddresses) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } } else { StringTokenizer st = new StringTokenizer(overrideEmail, ","); while (st.hasMoreTokens()) { msg.addRecipient(Message.RecipientType.TO, new InternetAddress(st.nextToken())); } } StringBuilder subject = new StringBuilder(configuration.getEmailSetup().getSubject()); subject.append(" - Platform: "); if (testSuite != null) { subject.append(testSuite.getPlatformName()); subject.append(", TestSuite: "); subject.append(testSuite.getName()); } else { subject.append(testHeader.getPlatformName()); subject.append(", Test: "); subject.append(testHeader.getTestName()); } subject.append(" - [errors="); subject.append(errorCount); subject.append(", warnings="); subject.append(warningCount); subject.append(", successes="); subject.append(successCount); subject.append("]"); msg.setSubject(subject.toString()); StringBuilder msgtxt = new StringBuilder(256); msgtxt.append("Please see test output in the following attached files:\n"); for (File f : testResults) { msgtxt.append(f.getName()); msgtxt.append("\n"); } // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(msgtxt.toString()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); for (File f : testResults) { if (f.exists() && f.isFile()) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message mbp2.setDataHandler(new DataHandler(new FileDataSource(f))); mbp2.setFileName(f.getName()); mp.addBodyPart(mbp2); } } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); Transport.send(msg); } catch (MessagingException ex) { LOG.warn(ex.toString(), ex); } } } }
From source file:cl.cnsv.wsreporteproyeccion.service.ReporteProyeccionServiceImpl.java
@Override public OutputObtenerCotizacionInternetVO obtenerCotizacionInternet(InputObtenerCotizacionInternetVO input) { //<editor-fold defaultstate="collapsed" desc="Inicio"> LOGGER.info("Iniciando el metodo obtenerCotizacionInternet..."); OutputObtenerCotizacionInternetVO output = new OutputObtenerCotizacionInternetVO(); String codigo;//from w ww.j a v a 2s . c om String mensaje; XStream xStream = new XStream(); //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Validacion de entrada"> OutputVO outputValidacion = validator.validarObtenerCotizacionInternet(input); if (!Integer.valueOf(Propiedades.getFuncProperty("codigo.ok")).equals(outputValidacion.getCodigo())) { codigo = Integer.toString(outputValidacion.getCodigo()); mensaje = outputValidacion.getMensaje(); LOGGER.info(mensaje); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Ir a JasperServer"> String numeroCotizacion = input.getNumeroCotizacion(); InputCotizacionInternet inputCotizacionInternet = new InputCotizacionInternet(); inputCotizacionInternet.setIdCotizacion(numeroCotizacion); String xmlInputCotizacionInternet = xStream.toXML(inputCotizacionInternet); LOGGER.info("Llamado a jasperserver: \n" + xmlInputCotizacionInternet); servicioJasperServer = new ServicioJasperServerJerseyImpl(); ResultadoDocumentoVO outputJasperServer; try { outputJasperServer = servicioJasperServer.buscarArchivoByCotizacion(inputCotizacionInternet); String xmlOutputJasperServer = xStream.toXML(outputJasperServer); LOGGER.info("Respuesta de jasperserver: \n" + xmlOutputJasperServer); String codigoJasperServer = outputJasperServer.getCodigo(); if (!Propiedades.getFuncProperty("jasperserver.ok.codigo").equals(codigoJasperServer)) { codigo = Propiedades.getFuncProperty("jasperserver.error.codigo"); mensaje = Propiedades.getFuncProperty("jasperserver.error.mensaje"); LOGGER.info(mensaje + ": " + outputJasperServer.getMensaje()); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } } catch (Exception e) { codigo = Propiedades.getFuncProperty("jasperserver.error.codigo"); mensaje = Propiedades.getFuncProperty("jasperserver.error.mensaje"); LOGGER.error(mensaje + ": " + e.getMessage(), e); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Ir a buscar datos email al servicio cotizador vida"> ClienteServicioCotizadorVida clienteCotizadorVida; try { clienteCotizadorVida = new ClienteServicioCotizadorVida(); } catch (Exception e) { codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.login.codigo"); mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.login.mensaje"); LOGGER.error(mensaje + ": " + e.getMessage(), e); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //Se busca el nombre del asegurado, glosa del plan y numero de propuesta LOGGER.info("Llamado a getDatosEmailCotizacionInternet - cotizadorVida: \n" + xmlInputCotizacionInternet); OutputEmailCotizacionInternetVO outputEmail; try { outputEmail = clienteCotizadorVida.getDatosEmailCotizacionInternet(inputCotizacionInternet); String xmlOutputEmail = xStream.toXML(outputEmail); LOGGER.info("Respuesta de getDatosEmailCotizacionInternet - cotizadorVida: \n" + xmlOutputEmail); String codigoOutputEmail = outputEmail.getCodigo(); if (!Propiedades.getFuncProperty("ws.cotizadorvida.codigo.ok").equals(codigoOutputEmail)) { codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.codigo"); mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.mensaje"); LOGGER.info(mensaje + ": " + outputEmail.getMensaje()); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } } catch (Exception e) { codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.codigo"); mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.mensaje"); LOGGER.error(mensaje + ": " + e.getMessage(), e); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Enviar correo con documento adjunto"> String documento = outputJasperServer.getDocumento(); try { EmailVO datosEmail = outputEmail.getDatosEmail(); String htmlBody = Propiedades.getFuncProperty("email.html"); String nombreAsegurable = datosEmail.getNombreAsegurable(); if (nombreAsegurable == null) { nombreAsegurable = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[NOMBRE_ASEGURADO]", nombreAsegurable); String glosaPlan = datosEmail.getGlosaPlan(); if (glosaPlan == null) { glosaPlan = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[GLOSA_PLAN]", glosaPlan); String numeroPropuesta = datosEmail.getNumeroPropuesta(); if (numeroPropuesta == null) { numeroPropuesta = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[NRO_PROPUESTA]", numeroPropuesta); //Parametrizar imagenes String imgBulletBgVerde = Propiedades.getFuncProperty("email.images.bulletbgverde"); if (imgBulletBgVerde == null) { imgBulletBgVerde = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_BULLET_BG_VERDE]", imgBulletBgVerde); String imgFace = Propiedades.getFuncProperty("email.images.face"); if (imgFace == null) { imgFace = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_FACE]", imgFace); String imgTwitter = Propiedades.getFuncProperty("email.images.twitter"); if (imgTwitter == null) { imgTwitter = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_TWITTER]", imgTwitter); String imgYoutube = Propiedades.getFuncProperty("email.images.youtube"); if (imgYoutube == null) { imgYoutube = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_YOUTUBE]", imgYoutube); String imgMail15 = Propiedades.getFuncProperty("email.images.mail00115"); if (imgMail15 == null) { imgMail15 = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_MAIL_00115]", imgMail15); String imgFono = Propiedades.getFuncProperty("email.images.fono"); if (imgFono == null) { imgFono = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_FONO]", imgFono); String imgMail16 = Propiedades.getFuncProperty("email.images.mail00116"); if (imgMail16 == null) { imgMail16 = ""; } htmlBody = StringUtils.replace(htmlBody, "$P[IMG_MAIL_00116]", imgMail16); byte[] attachmentData = Base64.decodeBase64(documento); final String username = Propiedades.getKeyProperty("email.username"); final String encryptedPassword = Propiedades.getKeyProperty("email.password"); String privateKeyFile = Propiedades.getConfProperty("KEY"); CryptoUtil cryptoUtil = new CryptoUtil("", privateKeyFile); final String password = cryptoUtil.decryptData(encryptedPassword); final String auth = Propiedades.getFuncProperty("email.auth"); final String starttls = Propiedades.getFuncProperty("email.starttls"); final String host = Propiedades.getFuncProperty("email.host"); final String port = Propiedades.getFuncProperty("email.port"); //Log de datos de correo String strDatosCorreo = "username: " + username + "\n" + "auth: " + auth + "\n" + "host: " + host + "\n"; LOGGER.info("Datos correo: \n".concat(strDatosCorreo)); Properties props = new Properties(); props.put("mail.smtp.auth", auth); if (!"0".equals(starttls)) { props.put("mail.smtp.starttls.enable", starttls); } props.put("mail.smtp.host", host); if (!"0".equals(port)) { props.put("mail.smtp.port", port); } Session session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); String fileName = Propiedades.getFuncProperty("tmp.cotizacionInternet.file.name"); fileName = fileName.replaceAll("%s", numeroPropuesta); fileName = fileName + ".pdf"; // creates a new e-mail message Message msg = new MimeMessage(session); String from = Propiedades.getFuncProperty("email.from"); msg.setFrom(new InternetAddress(from)); //TODO considerar email de prueba o email del asegurado String emailTo; if ("1".equals(Propiedades.getFuncProperty("email.to.test"))) { emailTo = Propiedades.getFuncProperty("email.to.mail"); } else { emailTo = datosEmail.getEmail(); } InternetAddress[] toAddresses = { new InternetAddress(emailTo) }; msg.setRecipients(Message.RecipientType.TO, toAddresses); String subject = Propiedades.getFuncProperty("email.subject"); msg.setSubject(subject); msg.setSentDate(new Date()); // creates message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(htmlBody, "text/html"); // creates multi-part Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // adds attachments MimeBodyPart attachPart = new MimeBodyPart(); DataSource dataSource = new ByteArrayDataSource(attachmentData, "application/pdf"); attachPart.setDataHandler(new DataHandler(dataSource)); attachPart.setFileName(fileName); multipart.addBodyPart(attachPart); // sets the multi-part as e-mail's content msg.setContent(multipart); // sends the e-mail Transport.send(msg); } catch (Exception ex) { codigo = Propiedades.getFuncProperty("email.error.codigo"); mensaje = Propiedades.getFuncProperty("email.error.mensaje"); LOGGER.error(mensaje + ": " + ex.getMessage(), ex); output.setCodigo(codigo); output.setMensaje(mensaje); return output; } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Termino"> codigo = Propiedades.getFuncProperty("codigo.ok"); mensaje = Propiedades.getFuncProperty("mensaje.ok"); output.setCodigo(codigo); output.setMensaje(mensaje); return output; //</editor-fold> }