List of usage examples for javax.mail Message setFrom
public abstract void setFrom(Address address) throws MessagingException;
From source file:com.cabserver.handler.Admin.java
@POST @Path("forgot-password") @Produces(MediaType.TEXT_HTML)/*from ww w. ja va 2 s . c o m*/ public Response forgotPassword(String jsonData) { // String data = ""; HashMap<String, String> responseMap = new HashMap<String, String>(); try { // log.info("forgotPassword before decoding = " + jsonData); jsonData = (URLDecoder.decode(jsonData, "UTF-8")); // log.info("forgotPassword >>" + jsonData); // jsonData = jsonData.split("=")[1]; if (jsonData.contains("=")) { jsonData = jsonData.split("=")[1]; // log.info("forgotPassword >> data=" + jsonData); } log.info("forgotPassword >> json data=" + jsonData); if (jsonData != null && jsonData.length() > 1) { // Gson gson = new Gson(); JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject) parser.parse(jsonData); // LoginInfo result = new LoginInfo(); String phone = (String) obj.get("phone"); // String password = (String) obj.get("password"); // log.info("phone =" + phone); // log.info("password =" + password); if (phone != null) { UserMaster um = DatabaseManager.getEmailIdByPhone(phone); if (um != null) { log.info("forgotPassword >> Email fetched by phone number. HTTP code is 200."); responseMap.put("code", "200"); responseMap.put("msg", "Password is sent to your registered E-Mail ID."); responseMap.put("phone", phone); // responseMap.put("password", um.getPassword()); // responseMap.put("mailid", um.getMailId()); try { if (Boolean.parseBoolean(ConfigDetails.constants.get("LOCAL_MAIL_SEND"))) { Message message = new MimeMessage(CacheBuilder.session); message.setFrom(new InternetAddress("VikingTaxee@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(um.getMailId())); message.setSubject("VikingTaxee Account Password Information"); message.setText("Dear Customer You password is : " + "\n\n " + um.getPassword()); Transport.send(message); log.info("forgotPassword >> Password is sent to your registered E-Mail ID."); } else { TravelMaster tm = new TravelMaster(); tm.setFromMailId("VikingTaxee@gmail.com"); tm.setToMailId(um.getMailId()); tm.setSubject("VikingTaxee Account Password Information"); tm.setMailText(um.getPassword()); tm.setMailType( Integer.parseInt(ConfigDetails.constants.get("MAIL_TYPE_FORGOT_PASSWORD"))); CacheBuilder.mailSendingDataMap.put((long) new Random().nextInt(100000), tm); } } catch (Exception e) { throw new RuntimeException(e); } } else { log.info("forgotPassword >> Password reset not done. Please call customer Care."); responseMap.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE")); responseMap.put("msg", "Forgot password process can not be completed. Please call customer Care."); } } } } catch (Exception e) { e.printStackTrace(); } if (responseMap.size() < 1) { log.info("Login Error. HTTP bookingStatus code is " + ConfigDetails.constants.get("BOOKING_FAILED_CODE") + "."); responseMap.put("code", ConfigDetails.constants.get("BOOKING_FAILED_CODE")); responseMap.put("msg", "Server Error."); return Response.status(200).entity(jsonCreater(responseMap)).build(); } else { return Response.status(200).entity(jsonCreater(responseMap)).build(); } }
From source file:org.entermedia.email.PostMail.java
public void postMail(List<InternetAddress> recipients, List<InternetAddress> blindrecipients, String subject, String inHtml, String inText, String from, List inAttachments, Map inProperties) throws MessagingException { // Set the host smtp address Properties props = new Properties(); // create some properties and get the default Session props.put("mail.smtp.host", fieldSmtpServer); props.put("mail.smtp.port", String.valueOf(getPort())); props.put("mail.smtp.auth", new Boolean(fieldSmtpSecured).toString()); if (isSslEnabled()) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); }/* w w w. ja va2 s.c o m*/ Session session = null; if (isEnableTls()) { props.put("mail.smtp.starttls.enable", "true"); session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(getSmtpUsername(), getSmtpPassword()); } }); } else if (fieldSmtpSecured) { SmtpAuthenticator auth = new SmtpAuthenticator(); session = Session.getInstance(props, auth); } else { session = Session.getInstance(props); } // session.setDebug(debug); // create a message Message msg = new MimeMessage(session); MimeMultipart mp = null; // msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, // "text/html"))); if (inAttachments != null && inAttachments.size() == 0) { inAttachments = null; } if (inText != null && inHtml != null || inAttachments != null) { // Create an "Alternative" Multipart message mp = new MimeMultipart("mixed"); if (inText != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(inText, "text/plain"); mp.addBodyPart(messageBodyPart); } if (inHtml != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(inHtml, "text/html"); mp.addBodyPart(messageBodyPart); } if (inAttachments != null) { for (Iterator iterator = inAttachments.iterator(); iterator.hasNext();) { String filename = (String) iterator.next(); File file = new File(filename); if (file.exists() && !file.isDirectory()) { // create the second message part MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(file); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); } } } msg.setContent(mp); } else if (inHtml != null) { msg.setContent(inHtml, "text/html"); } else { msg.setContent(inText, "text/plain"); } // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); //msg.setRecipient(RecipientType.BCC, addressFrom); msg.setSentDate(new Date()); if (recipients == null || recipients.isEmpty()) { throw new MessagingException("No recipients specified"); } InternetAddress[] addressTo = recipients.toArray(new InternetAddress[recipients.size()]); msg.setRecipients(Message.RecipientType.TO, addressTo); //add bcc if (blindrecipients != null && !blindrecipients.isEmpty()) { InternetAddress[] addressBcc = blindrecipients.toArray(new InternetAddress[blindrecipients.size()]); msg.setRecipients(Message.RecipientType.BCC, addressBcc); } // 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(subject); // Transport tr = session.getTransport("smtp"); // tr.connect(serverandport[0], null, null); // msg.saveChanges(); // don't forget this // tr.sendMessage(msg, msg.getAllRecipients()); // tr.close(); // msg.setContent(msg, "text/plain"); Transport.send(msg); log.info("sent email " + subject); }
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 www . j a v a2 s.co m 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> }
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//from w w w .j a v a 2 s . 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:com.panet.imeta.job.entries.mail.JobEntryMail.java
public Result execute(Result result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); File masterZipfile = null;/*w w w . j av a 2 s. c o m*/ // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { log.logError(toString(), Messages.getString("JobMail.Error.HostNotSpecified")); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { if (secureConnectionType.equals("TLS")) { // Allow TLS authentication props.put("mail.smtp.starttls.enable", "true"); } else { protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version // Unknown props.put("mail.smtps.quitwait", "false"); } } props.put("mail." + protocol + ".host", environmentSubstitute(server)); if (!Const.isEmpty(port)) props.put("mail." + protocol + ".port", environmentSubstitute(port)); boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG; if (debug) props.put("mail.debug", "true"); if (usingAuthentication) { props.put("mail." + protocol + ".auth", "true"); /* * authenticator = new Authenticator() { protected * PasswordAuthentication getPasswordAuthentication() { return new * PasswordAuthentication( * StringUtil.environmentSubstitute(Const.NVL(authenticationUser, * "")), * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword * , "")) ); } }; */ } Session session = Session.getInstance(props); session.setDebug(debug); try { // create a message Message msg = new MimeMessage(session); // set message priority if (usePriority) { String priority_int = "1"; if (priority.equals("low")) { priority_int = "3"; } if (priority.equals("normal")) { priority_int = "2"; } msg.setHeader("X-Priority", priority_int); // (String)int // between 1= high // and 3 = low. msg.setHeader("Importance", importance); // seems to be needed for MS Outlook. // where it returns a string of high /normal /low. } // Set Mail sender (From) String sender_address = environmentSubstitute(replyAddress); if (!Const.isEmpty(sender_address)) { String sender_name = environmentSubstitute(replyName); if (!Const.isEmpty(sender_name)) sender_address = sender_name + '<' + sender_address + '>'; msg.setFrom(new InternetAddress(sender_address)); } else { throw new MessagingException(Messages.getString("JobMail.Error.ReplyEmailNotFilled")); } // set Reply to addresses String reply_to_address = environmentSubstitute(replyToAddresses); if (!Const.isEmpty(reply_to_address)) { // Split the mail-address: space separated String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) address[i] = new InternetAddress(reply_Address_List[i]); msg.setReplyTo(address); } // Split the mail-address: space separated String destinations[] = environmentSubstitute(destination).split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) address[i] = new InternetAddress(destinations[i]); msg.setRecipients(Message.RecipientType.TO, address); if (!Const.isEmpty(destinationCc)) { // Split the mail-address Cc: space separated String destinationsCc[] = environmentSubstitute(destinationCc).split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) addressCc[i] = new InternetAddress(destinationsCc[i]); msg.setRecipients(Message.RecipientType.CC, addressCc); } if (!Const.isEmpty(destinationBCc)) { // Split the mail-address BCc: space separated String destinationsBCc[] = environmentSubstitute(destinationBCc).split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) addressBCc[i] = new InternetAddress(destinationsBCc[i]); msg.setRecipients(Message.RecipientType.BCC, addressBCc); } String realSubject = environmentSubstitute(subject); if (!Const.isEmpty(realSubject)) { msg.setSubject(realSubject); } msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) { messageText.append(environmentSubstitute(comment)).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append(Messages.getString("JobMail.Log.Comment.Job")).append(Const.CR); messageText.append("-----").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobName") + " : ") .append(parentJob.getJobMeta().getName()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobDirectory") + " : ") .append(parentJob.getJobMeta().getDirectory()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobEntry") + " : ").append(getName()) .append(Const.CR); messageText.append(Const.CR); } if (includeDate) { messageText.append(Const.CR).append(Messages.getString("JobMail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR); } if (!onlySendComment && result != null) { messageText.append(Messages.getString("JobMail.Log.Comment.PreviousResult") + ":").append(Const.CR); messageText.append("-----------------").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobEntryNr") + " : ") .append(result.getEntryNr()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Errors") + " : ") .append(result.getNrErrors()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesRead") + " : ") .append(result.getNrLinesRead()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesWritten") + " : ") .append(result.getNrLinesWritten()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesInput") + " : ") .append(result.getNrLinesInput()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesOutput") + " : ") .append(result.getNrLinesOutput()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesUpdated") + " : ") .append(result.getNrLinesUpdated()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Status") + " : ") .append(result.getExitStatus()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Result") + " : ") .append(result.getResult()).append(Const.CR); messageText.append(Const.CR); } if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson)) || !Const.isEmpty(environmentSubstitute(contactPhone)))) { messageText.append(Messages.getString("JobMail.Log.Comment.ContactInfo") + " :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.PersonToContact") + " : ") .append(environmentSubstitute(contactPerson)).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Tel") + " : ") .append(environmentSubstitute(contactPhone)).append(Const.CR); messageText.append(Const.CR); } // Include the path to this job entry... if (!onlySendComment) { JobTracker jobTracker = parentJob.getJobTracker(); if (jobTracker != null) { messageText.append(Messages.getString("JobMail.Log.Comment.PathToJobentry") + ":") .append(Const.CR); messageText.append("------------------------").append(Const.CR); addBacktracking(jobTracker, messageText); } } Multipart parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // 1st part if (useHTML) { if (!Const.isEmpty(getEncoding())) { part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding()); } else { part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } } else part1.setText(messageText.toString()); parts.addBodyPart(part1); if (includingFiles && result != null) { List<ResultFile> resultFiles = result.getResultFilesList(); if (resultFiles != null && !resultFiles.isEmpty()) { if (!zipFiles) { // Add all files to the message... // for (ResultFile resultFile : resultFiles) { FileObject file = resultFile.getFile(); if (file != null && file.exists()) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { // create a data source MimeBodyPart files = new MimeBodyPart(); URLDataSource fds = new URLDataSource(file.getURL()); // get a data Handler to manipulate this // file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(file.getName().getBaseName()); // add the part with the file in the // BodyPart(); parts.addBodyPart(files); log.logBasic(toString(), "Added file '" + fds.getName() + "' to the mail message."); } } } } else { // create a single ZIP archive of all files masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (ResultFile resultFile : resultFiles) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { FileObject file = resultFile.getFile(); ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into // this archive... BufferedInputStream inputStream = new BufferedInputStream( KettleVFS.getInputStream(file)); int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } inputStream.close(); zipOutputStream.closeEntry(); log.logBasic(toString(), "Added file '" + file.getName().getURI() + "' to the mail message in a zip archive."); } } } catch (Exception e) { log.logError(toString(), "Error zipping attachement files into file [" + masterZipfile.getPath() + "] : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { log.logError(toString(), "Unable to close attachement zip file archive : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } } } // Now attach the master zip file to the message. if (result.getNrErrors() == 0) { // create a data source MimeBodyPart files = new MimeBodyPart(); FileDataSource fds = new FileDataSource(masterZipfile); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in th e data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); } } } } msg.setContent(parts); Transport transport = null; try { transport = session.getTransport(protocol); if (usingAuthentication) { if (!Const.isEmpty(port)) { transport.connect(environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))), environmentSubstitute(Const.NVL(authenticationUser, "")), environmentSubstitute(Const.NVL(authenticationPassword, ""))); } else { transport.connect(environmentSubstitute(Const.NVL(server, "")), environmentSubstitute(Const.NVL(authenticationUser, "")), environmentSubstitute(Const.NVL(authenticationPassword, ""))); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) transport.close(); } } catch (IOException e) { log.logError(toString(), "Problem while sending message: " + e.toString()); result.setNrErrors(1); } catch (MessagingException mex) { log.logError(toString(), "Problem while sending message: " + mex.toString()); result.setNrErrors(1); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { log.logError(toString(), " ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) { log.logError(toString(), " " + invalid[i]); result.setNrErrors(1); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { log.logError(toString(), " ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) { log.logError(toString(), " " + validUnsent[i]); result.setNrErrors(1); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { // System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) { log.logError(toString(), " " + validSent[i]); result.setNrErrors(1); } } } if (ex instanceof MessagingException) { ex = ((MessagingException) ex).getNextException(); } else { ex = null; } } while (ex != null); } finally { if (masterZipfile != null && masterZipfile.exists()) { masterZipfile.delete(); } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } return result; }
From source file:FirstStatMain.java
private void btnsendemailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsendemailActionPerformed final String senderemail = txtEmailfrom.getText(); final String sendPass = txtPassword.getText(); String send_to = txtEmailto.getText(); String email_sub = txtemailsbj.getText(); String email_body = tABody.getText(); Properties prop = new Properties(); prop.put("mail.smtp.host", "smtp.gmail.com"); prop.put("mail.smtp.socketFactory.port", "465"); prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.port", "465"); Session session = Session.getDefaultInstance(prop, new javax.mail.Authenticator() { @Override//w w w.j a v a2 s . c om protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(senderemail, sendPass); } }); try { /* Message Header*/ Message message = new MimeMessage(session); message.setFrom(new InternetAddress(senderemail)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(send_to)); message.setSubject(email_sub); /*setting text message*/ MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(email_body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); /*attaching file*/ messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(file_path); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(txtattachmentname.getText()); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport.send(message); JOptionPane.showMessageDialog(rootPane, "Message sent"); } catch (Exception e) { JOptionPane.showMessageDialog(rootPane, e); } }
From source file:org.pentaho.di.job.entries.mail.JobEntryMail.java
public Result execute(Result result, int nr) { File masterZipfile = null;//from ww w .j a v a 2 s. c o m // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { logError(BaseMessages.getString(PKG, "JobMail.Error.HostNotSpecified")); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { if (secureConnectionType.equals("TLS")) { // Allow TLS authentication props.put("mail.smtp.starttls.enable", "true"); } else { protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version Unknown props.put("mail.smtps.quitwait", "false"); } } props.put("mail." + protocol + ".host", environmentSubstitute(server)); if (!Const.isEmpty(port)) { props.put("mail." + protocol + ".port", environmentSubstitute(port)); } if (log.isDebug()) { props.put("mail.debug", "true"); } if (usingAuthentication) { props.put("mail." + protocol + ".auth", "true"); /* * authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new * PasswordAuthentication( StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")) ); } }; */ } Session session = Session.getInstance(props); session.setDebug(log.isDebug()); try { // create a message Message msg = new MimeMessage(session); // set message priority if (usePriority) { String priority_int = "1"; if (priority.equals("low")) { priority_int = "3"; } if (priority.equals("normal")) { priority_int = "2"; } msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low. msg.setHeader("Importance", importance); // seems to be needed for MS Outlook. // where it returns a string of high /normal /low. msg.setHeader("Sensitivity", sensitivity); // Possible values are normal, personal, private, company-confidential } // Set Mail sender (From) String sender_address = environmentSubstitute(replyAddress); if (!Const.isEmpty(sender_address)) { String sender_name = environmentSubstitute(replyName); if (!Const.isEmpty(sender_name)) { sender_address = sender_name + '<' + sender_address + '>'; } msg.setFrom(new InternetAddress(sender_address)); } else { throw new MessagingException(BaseMessages.getString(PKG, "JobMail.Error.ReplyEmailNotFilled")); } // set Reply to addresses String reply_to_address = environmentSubstitute(replyToAddresses); if (!Const.isEmpty(reply_to_address)) { // Split the mail-address: space separated String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) { address[i] = new InternetAddress(reply_Address_List[i]); } msg.setReplyTo(address); } // Split the mail-address: space separated String[] destinations = environmentSubstitute(destination).split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) { address[i] = new InternetAddress(destinations[i]); } msg.setRecipients(Message.RecipientType.TO, address); String realCC = environmentSubstitute(getDestinationCc()); if (!Const.isEmpty(realCC)) { // Split the mail-address Cc: space separated String[] destinationsCc = realCC.split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) { addressCc[i] = new InternetAddress(destinationsCc[i]); } msg.setRecipients(Message.RecipientType.CC, addressCc); } String realBCc = environmentSubstitute(getDestinationBCc()); if (!Const.isEmpty(realBCc)) { // Split the mail-address BCc: space separated String[] destinationsBCc = realBCc.split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) { addressBCc[i] = new InternetAddress(destinationsBCc[i]); } msg.setRecipients(Message.RecipientType.BCC, addressBCc); } String realSubject = environmentSubstitute(subject); if (!Const.isEmpty(realSubject)) { msg.setSubject(realSubject); } msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); String endRow = isUseHTML() ? "<br>" : Const.CR; String realComment = environmentSubstitute(comment); if (!Const.isEmpty(realComment)) { messageText.append(realComment).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Job")).append(endRow); messageText.append("-----").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobName") + " : ") .append(parentJob.getJobMeta().getName()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobDirectory") + " : ") .append(parentJob.getJobMeta().getRepositoryDirectory()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntry") + " : ") .append(getName()).append(endRow); messageText.append(Const.CR); } if (includeDate) { messageText.append(endRow).append(BaseMessages.getString(PKG, "JobMail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(endRow).append(endRow); } if (!onlySendComment && result != null) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PreviousResult") + ":") .append(endRow); messageText.append("-----------------").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntryNr") + " : ") .append(result.getEntryNr()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Errors") + " : ") .append(result.getNrErrors()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRead") + " : ") .append(result.getNrLinesRead()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesWritten") + " : ") .append(result.getNrLinesWritten()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesInput") + " : ") .append(result.getNrLinesInput()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesOutput") + " : ") .append(result.getNrLinesOutput()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesUpdated") + " : ") .append(result.getNrLinesUpdated()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRejected") + " : ") .append(result.getNrLinesRejected()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Status") + " : ") .append(result.getExitStatus()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Result") + " : ") .append(result.getResult()).append(endRow); messageText.append(endRow); } if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson)) || !Const.isEmpty(environmentSubstitute(contactPhone)))) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.ContactInfo") + " :") .append(endRow); messageText.append("---------------------").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PersonToContact") + " : ") .append(environmentSubstitute(contactPerson)).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Tel") + " : ") .append(environmentSubstitute(contactPhone)).append(endRow); messageText.append(endRow); } // Include the path to this job entry... if (!onlySendComment) { JobTracker jobTracker = parentJob.getJobTracker(); if (jobTracker != null) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PathToJobentry") + ":") .append(endRow); messageText.append("------------------------").append(endRow); addBacktracking(jobTracker, messageText); if (isUseHTML()) { messageText.replace(0, messageText.length(), messageText.toString().replace(Const.CR, endRow)); } } } MimeMultipart parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // Attached files counter int nrattachedFiles = 0; // 1st part if (useHTML) { if (!Const.isEmpty(getEncoding())) { part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding()); } else { part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } } else { part1.setText(messageText.toString()); } parts.addBodyPart(part1); if (includingFiles && result != null) { List<ResultFile> resultFiles = result.getResultFilesList(); if (resultFiles != null && !resultFiles.isEmpty()) { if (!zipFiles) { // Add all files to the message... // for (ResultFile resultFile : resultFiles) { FileObject file = resultFile.getFile(); if (file != null && file.exists()) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) { found = true; } } if (found) { // create a data source MimeBodyPart files = new MimeBodyPart(); URLDataSource fds = new URLDataSource(file.getURL()); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(file.getName().getBaseName()); // insist on base64 to preserve line endings files.addHeader("Content-Transfer-Encoding", "base64"); // add the part with the file in the BodyPart(); parts.addBodyPart(files); nrattachedFiles++; logBasic("Added file '" + fds.getName() + "' to the mail message."); } } } } else { // create a single ZIP archive of all files masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (ResultFile resultFile : resultFiles) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) { found = true; } } if (found) { FileObject file = resultFile.getFile(); ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into this archive... BufferedInputStream inputStream = new BufferedInputStream( KettleVFS.getInputStream(file)); try { int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } } finally { inputStream.close(); } zipOutputStream.closeEntry(); nrattachedFiles++; logBasic("Added file '" + file.getName().getURI() + "' to the mail message in a zip archive."); } } } catch (Exception e) { logError("Error zipping attachement files into file [" + masterZipfile.getPath() + "] : " + e.toString()); logError(Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { logError("Unable to close attachement zip file archive : " + e.toString()); logError(Const.getStackTracker(e)); result.setNrErrors(1); } } } // Now attach the master zip file to the message. if (result.getNrErrors() == 0) { // create a data source MimeBodyPart files = new MimeBodyPart(); FileDataSource fds = new FileDataSource(masterZipfile); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); } } } } int nrEmbeddedImages = 0; if (embeddedimages != null && embeddedimages.length > 0) { FileObject imageFile = null; for (int i = 0; i < embeddedimages.length; i++) { String realImageFile = environmentSubstitute(embeddedimages[i]); String realcontenID = environmentSubstitute(contentids[i]); if (messageText.indexOf("cid:" + realcontenID) < 0) { if (log.isDebug()) { log.logDebug("Image [" + realImageFile + "] is not used in message body!"); } } else { try { boolean found = false; imageFile = KettleVFS.getFileObject(realImageFile, this); if (imageFile.exists() && imageFile.getType() == FileType.FILE) { found = true; } else { log.logError("We can not find [" + realImageFile + "] or it is not a file"); } if (found) { // Create part for the image MimeBodyPart messageBodyPart = new MimeBodyPart(); // Load the image URLDataSource fds = new URLDataSource(imageFile.getURL()); messageBodyPart.setDataHandler(new DataHandler(fds)); // Setting the header messageBodyPart.setHeader("Content-ID", "<" + realcontenID + ">"); // Add part to multi-part parts.addBodyPart(messageBodyPart); nrEmbeddedImages++; log.logBasic("Image '" + fds.getName() + "' was embedded in message."); } } catch (Exception e) { log.logError( "Error embedding image [" + realImageFile + "] in message : " + e.toString()); log.logError(Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (imageFile != null) { try { imageFile.close(); } catch (Exception e) { /* Ignore */ } } } } } } if (nrEmbeddedImages > 0 && nrattachedFiles == 0) { // If we need to embedd images... // We need to create a "multipart/related" message. // otherwise image will appear as attached file parts.setSubType("related"); } // put all parts together msg.setContent(parts); Transport transport = null; try { transport = session.getTransport(protocol); String authPass = getPassword(authenticationPassword); if (usingAuthentication) { if (!Const.isEmpty(port)) { transport.connect(environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))), environmentSubstitute(Const.NVL(authenticationUser, "")), authPass); } else { transport.connect(environmentSubstitute(Const.NVL(server, "")), environmentSubstitute(Const.NVL(authenticationUser, "")), authPass); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) { transport.close(); } } } catch (IOException e) { logError("Problem while sending message: " + e.toString()); result.setNrErrors(1); } catch (MessagingException mex) { logError("Problem while sending message: " + mex.toString()); result.setNrErrors(1); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { logError(" ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) { logError(" " + invalid[i]); result.setNrErrors(1); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { logError(" ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) { logError(" " + validUnsent[i]); result.setNrErrors(1); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { // System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) { logError(" " + validSent[i]); result.setNrErrors(1); } } } if (ex instanceof MessagingException) { ex = ((MessagingException) ex).getNextException(); } else { ex = null; } } while (ex != null); } finally { if (masterZipfile != null && masterZipfile.exists()) { masterZipfile.delete(); } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } return result; }
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 w w w . jav a 2 s . c o 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:Implement.Service.ProviderServiceImpl.java
@Override public boolean sendEmailReferral(String data, int providerID, String baseUrl) throws MessagingException { final String username = "registration@youtripper.com"; final String password = "Tripregister190515"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "mail.youtripper.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }/*from w w w . j a v a 2 s.c o m*/ }); String title = "You have an invitation from your friend."; JsonObject jsonObject = gson.fromJson(data, JsonObject.class); String content = jsonObject.get("content").getAsString(); JsonArray sportsArray = jsonObject.get("emails").getAsJsonArray(); ArrayList<String> listEmail = new ArrayList<>(); if (sportsArray != null) { for (int i = 0; i < sportsArray.size(); i++) { listEmail.add(sportsArray.get(i).getAsString()); } } String path = System.getProperty("catalina.base"); MimeBodyPart backgroundImage = new MimeBodyPart(); // attach the file to the message DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png")); backgroundImage.setDataHandler(new DataHandler(source)); backgroundImage.setFileName("backgroundImage.png"); backgroundImage.setDisposition(MimeBodyPart.INLINE); backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid MimeBodyPart giftImage = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png")); giftImage.setDataHandler(new DataHandler(source)); giftImage.setFileName("emailGift.png"); giftImage.setDisposition(MimeBodyPart.INLINE); giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(content, "US-ASCII", "html"); Multipart mp = new MimeMultipart("related"); mp.addBodyPart(mbp1); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("registration@youtripper.com")); String addresses = ""; for (int i = 0; i < listEmail.size(); i++) { if (i < listEmail.size() - 1) { addresses = addresses + listEmail.get(i) + ","; } else { addresses = addresses + listEmail.get(i); } } message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addresses)); message.setSubject(title); message.setContent(mp); message.saveChanges(); try { Transport.send(message); } catch (Exception e) { e.printStackTrace(); } System.out.println("sent"); return true; }
From source file:Implement.Service.ProviderServiceImpl.java
@Override public boolean sendMail(HttpServletRequest request, String providerName, int providerID, String baseUrl) throws MessagingException { final String username = "registration@youtripper.com"; final String password = "Tripregister190515"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtpm.csloxinfo.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }/*from www.j ava 2 s .c om*/ }); //Create data for referral java.util.Date date = new java.util.Date(); String s = providerID + (new Timestamp(date.getTime()).toString()); MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ProviderServiceImpl.class.getName()).log(Level.SEVERE, null, ex); } m.update(s.getBytes(), 0, s.length()); String md5 = (new BigInteger(1, m.digest()).toString(16)); String title = "You have an invitation from your friend."; String receiver = request.getParameter("email"); // StringBuilder messageContentHtml = new StringBuilder(); // messageContentHtml.append(request.getParameter("message") + "<br />\n"); // messageContentHtml.append("You can become a provider from here: " + baseUrl + "/Common/Provider/SignupReferral/" + md5); // String messageContent = messageContentHtml.toString(); String emailContent = " <div style='background: url(cid:bg_Icon) no-repeat;background-color:#ebebec;text-align: center;width:610px;height:365px'>" + " <p style='font-size:16px;padding-top: 45px; padding-bottom: 15px;'>Your friend <b>" + providerName + "</b> has invited you to complete purchase via</p>" + " <a href='http://youtripper.com/Common/Provider/SignupReferral/" + md5 + "' style='width: 160px;height: 50px;border-radius: 5px;border: 0;" + " background-color: #ff514e;font-size: 14px;font-weight: bolder;color: #fff;display: block;line-height: 50px;margin: 0 auto;text-decoration:none;' >Refferal Link</a>" + " <p style='font-size:16px;margin:30px;'><b>" + providerName + "</b> will get 25 credit</p>" + " <a href='http://youtripper.com' target='_blank'><img src='cid:gift_Icon' width='90' height='90'></a>" + " <a href='http://youtripper.com' target='_blank' style='font-size:10px;color:#939598;text-decoration:none'><p>from www.youtripper.com</p></a>" + " " + " " + " </div>"; String path = System.getProperty("catalina.base"); MimeBodyPart backgroundImage = new MimeBodyPart(); // attach the file to the message DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png")); backgroundImage.setDataHandler(new DataHandler(source)); backgroundImage.setFileName("backgroundImage.png"); backgroundImage.setDisposition(MimeBodyPart.INLINE); backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid MimeBodyPart giftImage = new MimeBodyPart(); // attach the file to the message source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png")); giftImage.setDataHandler(new DataHandler(source)); giftImage.setFileName("emailGift.png"); giftImage.setDisposition(MimeBodyPart.INLINE); giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(emailContent, "US-ASCII", "html"); Multipart mp = new MimeMultipart("related"); mp.addBodyPart(mbp1); mp.addBodyPart(backgroundImage); mp.addBodyPart(giftImage); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("registration@youtripper.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver)); message.setSubject(title); message.setContent(mp); message.saveChanges(); Transport.send(message); ReferralDTO referral = new ReferralDTO(providerID, receiver, String.valueOf(System.currentTimeMillis()), md5, 0); referralDAO.insertNewReferral(referral); return true; }