List of usage examples for javax.mail Message setRecipients
public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException;
From source file:it.eng.spagobi.tools.scheduler.dispatcher.MailDocumentDispatchChannel.java
public boolean dispatch(BIObject document, byte[] executionOutput) { Map parametersMap;/*from www . ja v a 2 s . c o m*/ String contentType; String fileExtension; IDataStore emailDispatchDataStore; String nameSuffix; String descriptionSuffix; String containedFileName; String zipFileName; boolean reportNameInSubject; logger.debug("IN"); try { parametersMap = dispatchContext.getParametersMap(); contentType = dispatchContext.getContentType(); fileExtension = dispatchContext.getFileExtension(); emailDispatchDataStore = dispatchContext.getEmailDispatchDataStore(); nameSuffix = dispatchContext.getNameSuffix(); descriptionSuffix = dispatchContext.getDescriptionSuffix(); containedFileName = dispatchContext.getContainedFileName() != null && !dispatchContext.getContainedFileName().equals("") ? dispatchContext.getContainedFileName() : document.getName(); zipFileName = dispatchContext.getZipMailName() != null && !dispatchContext.getZipMailName().equals("") ? dispatchContext.getZipMailName() : document.getName(); reportNameInSubject = dispatchContext.isReportNameInSubject(); String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl); //Custom Trusted Store Certificate Options String trustedStorePath = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.file"); String trustedStorePassword = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.password"); int smptPort = 25; if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } 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("")) { logger.debug("Smtp user not configured"); user = null; } // throw new Exception("Smtp user not configured"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) { logger.debug("Smtp password not configured"); } // throw new Exception("Smtp password not configured"); String mailSubj = dispatchContext.getMailSubj(); mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false); String mailTxt = dispatchContext.getMailTxt(); String[] recipients = findRecipients(dispatchContext, document, emailDispatchDataStore); if (recipients == null || recipients.length == 0) { logger.error("No recipients found for email sending!!!"); return false; } //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", Integer.toString(smptPort)); // open session Session session = null; // create autheticator object Authenticator auth = null; if (user != null) { auth = new SMTPAuthenticator(user, pass); props.put("mail.smtp.auth", "true"); //SSL Connection if (smtpssl.equals("true")) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //props.put("mail.smtp.debug", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort)); if ((!StringUtilities.isEmpty(trustedStorePath))) { /* Dynamic configuration of trustedstore for CA * Using Custom SSLSocketFactory to inject certificates directly from specified files */ //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY); } else { //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY); } props.put("mail.smtp.socketFactory.fallback", "false"); } //session = Session.getDefaultInstance(props, auth); session = Session.getInstance(props, auth); //session.setDebug(true); //session.setDebugOut(null); logger.info("Session.getInstance(props, auth)"); } else { //session = Session.getDefaultInstance(props); session = Session.getInstance(props); logger.info("Session.getInstance(props)"); } // 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 String subject = mailSubj; if (reportNameInSubject) { subject += " " + document.getName() + nameSuffix; } msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt + "\n" + descriptionSuffix); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = null; //if zip requested if (dispatchContext.isZipMailDocument()) { mbp2 = zipAttachment(executionOutput, containedFileName, zipFileName, nameSuffix, fileExtension); } //else else { sds = new SchedulerDataSource(executionOutput, contentType, containedFileName + nameSuffix + fileExtension); mbp2.setDataHandler(new DataHandler(sds)); mbp2.setFileName(sds.getName()); } // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smptPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { //Use normal SMTP Transport.send(msg); } } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:org.sofun.platform.notification.NotificationServiceImpl.java
@Override public void sendEmail(Member member, Map<String, String> params) throws CoreException { final String emailsStr = params.get("emails"); String[] emails = null;//ww w . j av a2s . co m if (emailsStr != null) { emails = params.get("emails").split(","); } String format = params.get("format"); if (format == null) { format = "text/html"; } Message message = new MimeMessage(mailer); final String encodingOptions = format + "; charset=UTF-8"; try { message.setHeader("Content-Type", encodingOptions); String from = params.get("from"); if (from == null || from.equals("")) { message.setFrom(new InternetAddress(CoreConstants.SOFUN_MAIL_FROM)); } else { message.setFrom(new InternetAddress(from)); } InternetAddress to[] = null; if (emails == null) { to = new InternetAddress[1]; to[0] = new InternetAddress(member.getEmail()); } else { to = new InternetAddress[emails.length]; for (int i = 0; i < emails.length; i++) { to[i] = new InternetAddress(emails[i]); } } message.setRecipients(Message.RecipientType.TO, to); message.setSubject(params.get("subject")); String body = params.get("body"); if (body != null) { body = body.replaceAll("(\\r|\\n)", "<p/>"); } VelocityEngine ve = null; try { ve = getVelocityEngine(); } catch (Exception e) { throw new CoreException(e.getMessage()); } Template t = ve.getTemplate(params.get("templateId")); StringWriter writer = new StringWriter(); VelocityContext context = new VelocityContext(); // Add Member in velocity context. context.put("member", member); context.put("body", body); // Add all incoming params in velocity context. for (Map.Entry<String, String> entry : params.entrySet()) { context.put(entry.getKey(), entry.getValue()); } t.merge(context, writer); message.setContent(writer.toString(), encodingOptions); Transport.send(message); String logEmails; if (emails != null) { logEmails = emailsStr; } else { logEmails = member.getEmail(); } log.info("Sending an email to=" + logEmails); } catch (MessagingException e) { log.error("Failed to send an email. See error below."); throw new CoreException(e.getMessage()); } }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java
/** AFter all files are stored in temporary tabe takes them and sens as zip or as separate attachments * /*www. j a va 2 s.com*/ * @param mailOptions * @return */ public boolean sendFiles(Map<String, Object> mailOptions) { logger.debug("IN"); try { final String DEFAULT_SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; final String CUSTOM_SSL_FACTORY = "it.eng.spagobi.commons.services.DummySSLSocketFactory"; String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH); File tempFolder = new File(tempFolderPath); if (!tempFolder.exists() || !tempFolder.isDirectory()) { logger.error("Temp Folder " + tempFolderPath + " does not exist or is not a directory: stop sending mail"); return false; } String smtphost = null; String pass = null; String smtpssl = null; String trustedStorePath = null; String user = null; String from = null; int smtpPort = 25; try { smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpportS = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpportS + " use SSL: " + smtpssl); //Custom Trusted Store Certificate Options trustedStorePath = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.trustedStore.file"); if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpportS == null) || smtpportS.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smtpPort = Integer.parseInt(smtpportS); } from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) { logger.debug("Smtp user not configured"); user = null; } // throw new Exception("Smtp user not configured"); pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) { logger.debug("Smtp password not configured"); } // throw new Exception("Smtp password not configured"); } catch (Exception e) { logger.error("Some E-mail configuration not set in table sbi_config: check you have all settings.", e); throw new Exception( "Some E-mail configuration not set in table sbi_config: check you have all settings."); } String mailSubj = mailOptions.get(MAIL_SUBJECT) != null ? (String) mailOptions.get(MAIL_SUBJECT) : null; Map parametersMap = mailOptions.get(PARAMETERS_MAP) != null ? (Map) mailOptions.get(PARAMETERS_MAP) : null; mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false); String mailTxt = mailOptions.get(MAIL_TXT) != null ? (String) mailOptions.get(MAIL_TXT) : null; String[] recipients = mailOptions.get(RECIPIENTS) != null ? (String[]) mailOptions.get(RECIPIENTS) : null; //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.p ort", Integer.toString(smtpPort)); // open session Session session = null; // create autheticator object Authenticator auth = null; if (user != null) { auth = new SMTPAuthenticator(user, pass); props.put("mail.smtp.auth", "true"); //SSL Connection if (smtpssl.equals("true")) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //props.put("mail.smtp.debug", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.socketFactory.port", Integer.toString(smtpPort)); if ((!StringUtilities.isEmpty(trustedStorePath))) { /* Dynamic configuration of trustedstore for CA * Using Custom SSLSocketFactory to inject certificates directly from specified files */ //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY); } else { //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY); } props.put("mail.smtp.socketFactory.fallback", "false"); } //session = Session.getDefaultInstance(props, auth); session = Session.getInstance(props, auth); //session.setDebug(true); //session.setDebugOut(null); logger.info("Session.getInstance(props, auth)"); } else { //session = Session.getDefaultInstance(props); session = Session.getInstance(props); logger.info("Session.getInstance(props)"); } // 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 String subject = mailSubj; String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : null; Boolean reportNameInSubject = mailOptions.get(REPORT_NAME_IN_SUBJECT) != null && !mailOptions.get(REPORT_NAME_IN_SUBJECT).toString().equals("") ? (Boolean) mailOptions.get(REPORT_NAME_IN_SUBJECT) : null; //Boolean descriptionSuffix =mailOptions.get(DESCRIPTION_SUFFIX) != null && !mailOptions.get(DESCRIPTION_SUFFIX).toString().equals("")? (Boolean) mailOptions.get(DESCRIPTION_SUFFIX) : null; String zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME) : "Zipped Documents"; String contentType = mailOptions.get(CONTENT_TYPE) != null ? (String) mailOptions.get(CONTENT_TYPE) : null; String fileExtension = mailOptions.get(FILE_EXTENSION) != null ? (String) mailOptions.get(FILE_EXTENSION) : null; if (reportNameInSubject) { subject += " " + nameSuffix; } msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt); // attach the file to the message boolean isZipDocument = mailOptions.get(IS_ZIP_DOCUMENT) != null ? (Boolean) mailOptions.get(IS_ZIP_DOCUMENT) : false; zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME) : "Zipped Documents"; // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); if (isZipDocument) { logger.debug("Make zip"); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); mbp2 = zipAttachment(zipFileName, mailOptions, tempFolder); mp.addBodyPart(mbp2); } else { logger.debug("Attach single files"); SchedulerDataSource sds = null; MimeBodyPart bodyPart = null; try { String[] entries = tempFolder.list(); for (int i = 0; i < entries.length; i++) { logger.debug("Attach file " + entries[i]); File f = new File(tempFolder + File.separator + entries[i]); byte[] content = getBytesFromFile(f); bodyPart = new MimeBodyPart(); sds = new SchedulerDataSource(content, contentType, entries[i]); //sds = new SchedulerDataSource(content, contentType, entries[i] + fileExtension); bodyPart.setDataHandler(new DataHandler(sds)); bodyPart.setFileName(sds.getName()); mp.addBodyPart(bodyPart); } } catch (Exception e) { logger.error("Error while attaching files", e); } } // add the Multipart to the message msg.setContent(mp); logger.debug("Preparing to send mail"); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { logger.debug("Smtps mode active user " + user); //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smtpPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { logger.debug("Smtp mode"); //Use normal SMTP Transport.send(msg); } // logger.debug("delete tempFolder path "+tempFolder.getPath()); // boolean deleted = tempFolder.delete(); // logger.debug("Temp folder deleted "+deleted); } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
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;/* ww w . j a va 2 s. c o 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:userinterface.DoctorWorkArea.DiagnosePatientJPanel.java
private void addtoCartButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addtoCartButton6ActionPerformed // TODO add your handling code here: int selectedRow = productTable.getSelectedRow(); if (selectedRow < 0) { JOptionPane.showMessageDialog(null, "Please select a Product from the Table"); return;/*from www. j a v a 2s . co m*/ } Product product = (Product) productTable.getValueAt(selectedRow, 0); int quantity = (Integer) quantitySpinner.getValue(); if (quantity == 0) { JOptionPane.showMessageDialog(null, "Please enter a number for Medicine Quantity!"); return; } if (product != null) { updateQuantity(product, quantity, SUBTRACT); } String medName = product.getProdName(); Employee patient = (Employee) patientCombo1.getSelectedItem(); patient.getMedicalRecord().setMedicinePrescribed(medName); String email = patient.getEmail(); if (email.trim().isEmpty()) { JOptionPane.showMessageDialog(null, "Patient profile is not updated for email!"); return; } if (isValidEmailAddress(email)) { String uuid = UUID.randomUUID().toString(); //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample"); 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"); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("neelzsaxena@gmail.com", "painforever24"); } } ); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("neelzsaxena@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); message.setSubject("Prescribed Medicines"); message.setText("The medicine Prescribed is :" + medName + '\n' + "The Quantity authorized is:" + quantity + '\n' + "The unique barcode is:" + uuid); Transport.send(message); populateTable(); JOptionPane.showMessageDialog(null, "message sent"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "message failed"); } } else { JOptionPane.showMessageDialog(null, "Invalid Email Id"); return; } // String uuid = UUID.randomUUID().toString(); // //JOptionPane.showMessageDialog(null, "Barcode Generated and attached to the sample"); // // 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"); // // Session session = Session.getDefaultInstance(props, // new javax.mail.Authenticator(){ // protected PasswordAuthentication getPasswordAuthentication(){ // return new PasswordAuthentication("neelzsaxena@gmail.com", "painforever24"); // } // // } // // ); // try{ // Message message = new MimeMessage(session); // message.setFrom(new InternetAddress("neelzsaxena@gmail.com")); // message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email)); // message.setSubject("Prescribed Medicines"); // message.setText("The medicine Prescribed is :" +medName + '\n'+ // "The Quantity authorized is:"+quantity + '\n'+ // "The unique barcode is:"+uuid); // Transport.send(message); // populateTable(); // JOptionPane.showMessageDialog(null,"message sent"); // }catch(Exception e){ // JOptionPane.showMessageDialog(null,"message failed"); // } }
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 {// w w w .j a v a2s.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:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java
private void sendMail(DispatchContext sInfo, BIObject biobj, Map parMap, byte[] response, String retCT, String fileExt, IDataStore dataStore, String toBeAppendedToName, String toBeAppendedToDescription) { logger.debug("IN"); try {/*from w w w. ja v a 2s .c o m*/ String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); int smptPort = 25; if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } 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("")) { logger.debug("Smtp user not configured"); user = null; } // throw new Exception("Smtp user not configured"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) { logger.debug("Smtp password not configured"); } // throw new Exception("Smtp password not configured"); String mailSubj = sInfo.getMailSubj(); mailSubj = StringUtilities.substituteParametersInString(mailSubj, parMap, null, false); String mailTxt = sInfo.getMailTxt(); String[] recipients = findRecipients(sInfo, biobj, dataStore); if (recipients == null || recipients.length == 0) { logger.error("No recipients found for email sending!!!"); return; } //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", smptPort); // open session Session session = null; // create autheticator object Authenticator auth = null; if (user != null) { auth = new SMTPAuthenticator(user, pass); props.put("mail.smtp.auth", "true"); session = Session.getDefaultInstance(props, auth); logger.error("Session.getDefaultInstance(props, auth)"); } else { session = Session.getDefaultInstance(props); logger.error("Session.getDefaultInstance(props)"); } // 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 String subject = mailSubj + " " + biobj.getName() + toBeAppendedToName; msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt + "\n" + toBeAppendedToDescription); // 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:smilehouse.opensyncro.pipes.Pipe.java
private void addLogEntry(LogEntry logEntry, int statusCode) { if (this.log == null) this.log = new HashSet(); logEntry.setStatusCode(statusCode);//w w w . j a va 2s . c o m logEntry.setTime(new Date()); // The LogEntry is not explicitly added to the Pipe's log Set, since it causes // Hibernate to query all LogEntries from the database and thus consume // ever-increasing amount of server resources. //this.log.add(logEntry); String status = getStatusString(statusCode); Persister persister = new Persister(database); try { persister.update(logEntry); List messages; boolean mailAddressNotSet = ((getMailHost() == null || getRecipientAddress() == null) || (getMailHost().length() == 0 || getRecipientAddress().length() == 0)); // Notification via email only if host and email address are present if (!mailAddressNotSet && !(getTransferLogNotificationLevel() == MessageLogger.MAIL_NONE)) { String date = dateFormat.format(new Date()); String subject = this.getName() + " " + status + " " + date + " (" + database + ")"; String message = ""; // Get number of log messages at or below transferLogNotificationLevel. int entries = persister.getLogMessageEntries(logEntry.getId(), getTransferLogNotificationLevel()) .size(); //Generate mail message if (entries > 0) { messages = persister.getLogMessageEntries(logEntry.getId(), getLoggingVerbosityLevel()); for (Iterator m = messages.iterator(); m.hasNext();) { LogMessageEntry messageEntry = (LogMessageEntry) m.next(); message += (messageEntry.getMessage()) + "\n"; } } else { message += MAIL_MESSAGE_NO_ENTRIES; } // Send notification email except when the message is // MAIL_MESSAGE_NO_ENTRIES or the pipe has aborted and // isAbortMailEnabled()==true if (!message.equals(MAIL_MESSAGE_NO_ENTRIES) || (statusCode == LogEntry.STATUS_ABORTED && isAbortMailEnabled())) { try { Properties props = new Properties(); props.put("mail.host", getMailHost()); Session mailConnection = Session.getInstance(props, null); Message msg = new MimeMessage(mailConnection); Address sender = new InternetAddress(MAIL_SENDER + "@" + getMailHost(), MAIL_SENDER); Address[] receivers = receiverAddresses(getRecipientAddress()); // Set mail content and subject msg.setContent(message, "text/plain"); msg.setFrom(sender); msg.setRecipients(Message.RecipientType.TO, receivers); msg.setSubject(subject); // Send the mail Transport.send(msg); } catch (MessagingException e) { String error = "An error occurred when sending mail report from " + MAIL_SENDER + "@" + getMailHost() + " to " + getRecipientAddress() + ":\n" + e.getMessage(); Environment.getInstance().log(error); logEntry.logMessage(error, this, MessageLogger.ERROR); persister.update(logEntry); } catch (RuntimeException ex) { Environment.getInstance().log("A RuntimeException has occurred: " + ex.getMessage() + ex.getStackTrace().toString()); } } } // Remove unnecessary (debug level) messages from the LogEntry if Transfer log // verbosity level is set to DYNAMIC and the current LogEntry's status is either // OK or ABORTED if (getLoggingVerbosityLevel() == MessageLogger.LOG_DYNAMIC && (statusCode == LogEntry.STATUS_OK || statusCode == LogEntry.STATUS_ABORTED)) { messages = persister.getLogMessageEntries(logEntry.getId(), MessageLogger.DEBUG); if (messages.size() > 0) { for (Iterator m = messages.iterator(); m.hasNext();) { LogMessageEntry messageEntry = (LogMessageEntry) m.next(); if (messageEntry.getMessageType() == MessageLogger.DEBUG) { persister.delete(messageEntry); } } } } } catch (Exception e) { Environment.getInstance().log(e.getMessage()); } finally { persister.close(); } }
From source file:be.ibridge.kettle.job.entry.mail.JobEntryMail.java
public Result execute(Result result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); File masterZipfile = null;/*ww w .j av a2 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(), "Unable to send the mail because the mail-server (SMTP host) is not specified"); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { protocol = "smtps"; } props.put("mail." + protocol + ".host", StringUtil.environmentSubstitute(server)); if (!Const.isEmpty(port)) props.put("mail." + protocol + ".port", StringUtil.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); String email_address = StringUtil.environmentSubstitute(replyAddress); if (!Const.isEmpty(email_address)) { msg.setFrom(new InternetAddress(email_address)); } else { throw new MessagingException("reply e-mail address is not filled in"); } // Split the mail-address: space separated String destinations[] = StringUtil.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[] = StringUtil.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[] = StringUtil.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); } msg.setSubject(StringUtil.environmentSubstitute(subject)); msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) { messageText.append(StringUtil.environmentSubstitute(comment)).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append("Job:").append(Const.CR); messageText.append("-----").append(Const.CR); messageText.append("Name : ").append(parentJob.getJobMeta().getName()).append(Const.CR); messageText.append("Directory : ").append(parentJob.getJobMeta().getDirectory()).append(Const.CR); messageText.append("JobEntry : ").append(getName()).append(Const.CR); messageText.append(Const.CR); } if (includeDate) { Value date = new Value("date", new Date()); messageText.append("Message date: ").append(date.toString()).append(Const.CR).append(Const.CR); } if (!onlySendComment && result != null) { messageText.append("Previous result:").append(Const.CR); messageText.append("-----------------").append(Const.CR); messageText.append("Job entry nr : ").append(result.getEntryNr()).append(Const.CR); messageText.append("Errors : ").append(result.getNrErrors()).append(Const.CR); messageText.append("Lines read : ").append(result.getNrLinesRead()).append(Const.CR); messageText.append("Lines written : ").append(result.getNrLinesWritten()).append(Const.CR); messageText.append("Lines input : ").append(result.getNrLinesInput()).append(Const.CR); messageText.append("Lines output : ").append(result.getNrLinesOutput()).append(Const.CR); messageText.append("Lines updated : ").append(result.getNrLinesUpdated()).append(Const.CR); messageText.append("Script exit status : ").append(result.getExitStatus()).append(Const.CR); messageText.append("Result : ").append(result.getResult()).append(Const.CR); messageText.append(Const.CR); } if (!onlySendComment && (!Const.isEmpty(StringUtil.environmentSubstitute(contactPerson)) || !Const.isEmpty(StringUtil.environmentSubstitute(contactPhone)))) { messageText.append("Contact information :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append("Person to contact : ").append(StringUtil.environmentSubstitute(contactPerson)) .append(Const.CR); messageText.append("Telephone number : ").append(StringUtil.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("Path to this job entry:").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 part1.setText(messageText.toString()); parts.addBodyPart(part1); if (includingFiles && result != null) { List resultFiles = result.getResultFilesList(); if (resultFiles != null && resultFiles.size() > 0) { if (!zipFiles) { // Add all files to the message... // for (Iterator iter = resultFiles.iterator(); iter.hasNext();) { ResultFile resultFile = (ResultFile) iter.next(); 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(fds.getName()); // 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 + StringUtil.environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (Iterator iter = resultFiles.iterator(); iter.hasNext();) { ResultFile resultFile = (ResultFile) iter.next(); 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().getURI()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into this archive... BufferedInputStream inputStream = new BufferedInputStream( file.getContent().getInputStream()); 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(StringUtil.environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(StringUtil.environmentSubstitute(Const.NVL(port, ""))), StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, ""))); } else { transport.connect(StringUtil.environmentSubstitute(Const.NVL(server, "")), StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), StringUtil.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:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java
public static void sendMail(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList, Object FunctionContext) { boolean debug = false; // Arguments: // String smtp, String from, String recipients[ ], String subject, String message if (ArgList.length == 5) { try {// ww w. j a v a 2 s .co m //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((String) ArgList[4], "text/plain"); Transport.send(msg); } catch (Exception e) { throw new RuntimeException("sendMail: " + e.toString()); } } else { throw new RuntimeException("The function call sendMail requires 5 arguments."); } }