List of usage examples for javax.mail.internet MimeBodyPart setDataHandler
@Override public void setDataHandler(DataHandler dh) throws MessagingException
From source file:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java
public static MimeBodyPart zipAttachment(String zipFileName, Map mailOptions, File tempFolder) { logger.debug("IN"); MimeBodyPart messageBodyPart = null; try {// w w w. ja va2 s . co m String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : ""; byte[] buffer = new byte[4096]; // Create a buffer for copying int bytesRead; // the zip String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH); ByteArrayOutputStream bout = new ByteArrayOutputStream(); ZipOutputStream out = new ZipOutputStream(bout); logger.debug("File zip to write: " + tempFolderPath + File.separator + "zippedFile.zip"); //files to zip String[] entries = tempFolder.list(); for (int i = 0; i < entries.length; i++) { //File f = new File(tempFolder, entries[i]); File f = new File(tempFolder + File.separator + entries[i]); if (f.isDirectory()) continue;//Ignore directory logger.debug("insert file: " + f.getName()); FileInputStream in = new FileInputStream(f); // Stream to read file ZipEntry entry = new ZipEntry(f.getName()); // Make a ZipEntry out.putNextEntry(entry); // Store entry while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); } out.close(); messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(bout.toByteArray(), "application/zip"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(zipFileName + nameSuffix + ".zip"); } catch (Exception e) { logger.error("Error while creating the zip", e); return null; } logger.debug("OUT"); return messageBodyPart; }
From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java
@SuppressWarnings("deprecation") @Override/*from w w w . j a v a 2s . co m*/ public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) { HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD); String path = PropertyExpander.expandProperties(context, request.getPath()); StringBuffer query = new StringBuffer(); String encoding = System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding())); StringToStringMap responseProperties = (StringToStringMap) context .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES); MimeMultipart formMp = "multipart/form-data".equals(request.getMediaType()) && httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null; RestParamsPropertyHolder params = request.getParams(); for (int c = 0; c < params.getPropertyCount(); c++) { RestParamProperty param = params.getPropertyAt(c); String value = PropertyExpander.expandProperties(context, param.getValue()); responseProperties.put(param.getName(), value); List<String> valueParts = sendEmptyParameters(request) || (!StringUtils.hasContent(value) && param.getRequired()) ? RestUtils.splitMultipleParametersEmptyIncluded(value, request.getMultiValueDelimiter()) : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter()); // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by // the URI handling further down) if (value != null && param.getStyle() != ParameterStyle.HEADER && param.getStyle() != ParameterStyle.TEMPLATE && !param.isDisableUrlEncoding()) { try { if (StringUtils.hasContent(encoding)) { value = URLEncoder.encode(value, encoding); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding)); } else { value = URLEncoder.encode(value); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, URLEncoder.encode(valueParts.get(i))); } } catch (UnsupportedEncodingException e1) { SoapUI.logError(e1); value = URLEncoder.encode(value); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, URLEncoder.encode(valueParts.get(i))); } // URLEncoder replaces space with "+", but we want "%20". value = value.replaceAll("\\+", "%20"); for (int i = 0; i < valueParts.size(); i++) valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20")); } if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) { if (!StringUtils.hasContent(value) && !param.getRequired()) continue; } switch (param.getStyle()) { case HEADER: for (String valuePart : valueParts) httpMethod.addHeader(param.getName(), valuePart); break; case QUERY: if (formMp == null || !request.isPostQueryString()) { for (String valuePart : valueParts) { if (query.length() > 0) query.append('&'); query.append(URLEncoder.encode(param.getName())); query.append('='); if (StringUtils.hasContent(valuePart)) query.append(valuePart); } } else { try { addFormMultipart(request, formMp, param.getName(), responseProperties.get(param.getName())); } catch (MessagingException e) { SoapUI.logError(e); } } break; case TEMPLATE: try { value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } break; case MATRIX: try { value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } if (param.getType().equals(XmlBoolean.type.getName())) { if (value.toUpperCase().equals("TRUE") || value.equals("1")) { path += ";" + param.getName(); } } else { path += ";" + param.getName(); if (StringUtils.hasContent(value)) { path += "=" + value; } } case PLAIN: break; } } if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES)) path = PathUtils.fixForwardSlashesInPath(path); if (PathUtils.isHttpPath(path)) { try { // URI(String) automatically URLencodes the input, so we need to // decode it first... URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)); context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri); java.net.URI oldUri = httpMethod.getURI(); httpMethod.setURI(new java.net.URI(oldUri.getScheme(), oldUri.getUserInfo(), oldUri.getHost(), oldUri.getPort(), (uri.getPath()) == null ? "/" : uri.getPath(), oldUri.getQuery(), oldUri.getFragment())); } catch (Exception e) { SoapUI.logError(e); } } else if (StringUtils.hasContent(path)) { try { java.net.URI oldUri = httpMethod.getURI(); String pathToSet = StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath()) ? oldUri.getRawPath() + path : path; java.net.URI newUri = URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(), pathToSet, oldUri.getQuery(), oldUri.getFragment()); httpMethod.setURI(newUri); context.setProperty(BaseHttpRequestTransport.REQUEST_URI, new URI(newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS))); } catch (Exception e) { SoapUI.logError(e); } } if (query.length() > 0 && !request.isPostQueryString()) { try { java.net.URI oldUri = httpMethod.getURI(); httpMethod.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(), oldUri.getRawPath(), query.toString(), oldUri.getFragment())); } catch (Exception e) { SoapUI.logError(e); } } if (request instanceof RestRequest) { String acceptEncoding = ((RestRequest) request).getAccept(); if (StringUtils.hasContent(acceptEncoding)) { httpMethod.setHeader("Accept", acceptEncoding); } } if (formMp != null) { // create request message try { if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) { String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(), request.isEntitizeProperties()); if (StringUtils.hasContent(requestContent)) { initRootPart(request, requestContent, formMp); } } for (Attachment attachment : request.getAttachments()) { MimeBodyPart part = new PreencodedMimeBodyPart("binary"); if (attachment instanceof FileAttachment<?>) { String name = attachment.getName(); if (StringUtils.hasContent(attachment.getContentID()) && !name.equals(attachment.getContentID())) name = attachment.getContentID(); part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\""); } else part.setDisposition("form-data; name=\"" + attachment.getName() + "\""); part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment))); formMp.addBodyPart(part); } MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION); message.setContent(formMp); message.saveChanges(); RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity( message, request); ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity); httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue()); httpMethod.setHeader("MIME-Version", "1.0"); } catch (Throwable e) { SoapUI.logError(e); } } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) { if (StringUtils.hasContent(request.getMediaType())) httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding)); if (request.isPostQueryString()) { try { ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString())); } catch (UnsupportedEncodingException e) { SoapUI.logError(e); } } else { String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(), request.isEntitizeProperties()); List<Attachment> attachments = new ArrayList<Attachment>(); for (Attachment attachment : request.getAttachments()) { if (attachment.getContentType().equals(request.getMediaType())) { attachments.add(attachment); } } if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) { try { byte[] content = encoding == null ? requestContent.getBytes() : requestContent.getBytes(encoding); ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content)); } catch (UnsupportedEncodingException e) { ((HttpEntityEnclosingRequest) httpMethod) .setEntity(new ByteArrayEntity(requestContent.getBytes())); } } else if (attachments.size() > 0) { try { MimeMultipart mp = null; if (StringUtils.hasContent(requestContent)) { mp = new MimeMultipart(); initRootPart(request, requestContent, mp); } else if (attachments.size() == 1) { ((HttpEntityEnclosingRequest) httpMethod) .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1)); httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding)); } if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) { if (mp == null) mp = new MimeMultipart(); // init mimeparts AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap()); // create request message MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION); message.setContent(mp); message.saveChanges(); RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity( message, request); ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity); httpMethod.setHeader("Content-Type", getContentTypeHeader( mimeMessageRequestEntity.getContentType().getValue(), encoding)); httpMethod.setHeader("MIME-Version", "1.0"); } } catch (Exception e) { SoapUI.logError(e); } } } } }
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;/*from www.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)) { 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:it.eng.spagobi.tools.scheduler.jobs.CopyOfExecuteBIDocumentJob.java
private void sendToDl(DispatchContext sInfo, BIObject biobj, byte[] response, String retCT, String fileExt, String toBeAppendedToName, String toBeAppendedToDescription) { logger.debug("IN"); try {/*from w ww . j a va 2 s.c o m*/ 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 ww . ja va 2 s . 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:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java
public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) { // Retrieve SMTP server information String host = getSmtpHost();/* w w w.ja v a2 s.c om*/ boolean isSmtpAuthentication = isSmtpAuthentication(); int smtpPort = getSmtpPort(); String smtpUser = getSmtpUser(); String smtpPwd = getSmtpPwd(); boolean isSmtpDebug = isSmtpDebug(); List<String> emailErrors = new ArrayList<String>(); if (emails.size() > 0) { // Corps et sujet du message String subject = getString("infoLetter.emailSubject") + ilp.getName(); // Email du publieur String from = getUserDetail().geteMail(); // create some properties and get the default Session Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication)); Session session = Session.getInstance(props, null); session.setDebug(isSmtpDebug); // print on the console all SMTP messages. SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "subject = " + subject); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "from = " + from); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "host= " + host); try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject, CharEncoding.UTF_8); ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId()); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg, I18NHelper.defaultLanguage); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); for (SimpleDocument content : contents) { AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(), content.getLanguage()); } mbp1.setDataHandler( new DataHandler(new ByteArrayDataSource( replaceFileServerWithLocal( IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server), MimeTypes.HTML_MIME_TYPE))); IOUtils.closeQuietly(buffer); // Fichiers joints WAPrimaryKey publiPK = ilp.getPK(); publiPK.setComponentName(getComponentId()); publiPK.setSpace(getSpaceId()); // create the Multipart and its parts to it String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related"); Multipart mp = new MimeMultipart(mimeMultipart); mp.addBodyPart(mbp1); // Images jointes List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null); for (SimpleDocument attachment : fichiers) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment.getAttachmentPath()); mbp2.setDataHandler(new DataHandler(fds)); // For Displaying images in the mail mbp2.setFileName(attachment.getFilename()); mbp2.setHeader("Content-ID", attachment.getFilename()); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID()); // create the Multipart and its parts to it mp.addBodyPart(mbp2); } // Fichiers joints fichiers = AttachmentServiceFactory.getAttachmentService() .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null); if (!fichiers.isEmpty()) { for (SimpleDocument attachment : fichiers) { // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(attachment.getAttachmentPath()); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(attachment.getFilename()); // For Displaying images in the mail mbp2.setHeader("Content-ID", attachment.getFilename()); SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID()); // create the Multipart and its parts to it mp.addBodyPart(mbp2); } } // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); // create a Transport connection (TCP) Transport transport = session.getTransport("smtp"); InternetAddress[] address = new InternetAddress[1]; for (String email : emails) { try { address[0] = new InternetAddress(email); msg.setRecipients(Message.RecipientType.TO, address); // add Transport Listener to the transport connection. if (isSmtpAuthentication) { SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser); transport.connect(host, smtpPort, smtpUser, smtpPwd); msg.saveChanges(); } else { transport.connect(); } transport.sendMessage(msg, address); } catch (Exception ex) { SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.MSG_GEN_PARAM_VALUE", "Email = " + email, new InfoLetterException( "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController", SilverpeasRuntimeException.ERROR, ex.getMessage(), ex)); emailErrors.add(email); } finally { if (transport != null) { try { transport.close(); } catch (Exception e) { SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()", "root.EX_IGNORED", "ClosingTransport", e); } } } } } catch (Exception e) { throw new InfoLetterException( "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController", SilverpeasRuntimeException.ERROR, e.getMessage(), e); } } return emailErrors.toArray(new String[emailErrors.size()]); }
From source file:org.pentaho.di.trans.steps.mail.Mail.java
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (MailMeta) smi;//from ww w . ja v a2s .c o m data = (MailData) sdi; Object[] r = getRow(); // get row, set busy! if (r == null) { // no more input to be expected... setOutputDone(); return false; } if (first) { first = false; // get the RowMeta data.previousRowMeta = getInputRowMeta().clone(); // Check is filename field is provided if (Const.isEmpty(meta.getDestination())) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.DestinationFieldEmpty")); } // Check is replyname field is provided if (Const.isEmpty(meta.getReplyAddress())) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.ReplyFieldEmpty")); } // Check is SMTP server is provided if (Const.isEmpty(meta.getServer())) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.ServerFieldEmpty")); } // Check Attached filenames when dynamic if (meta.isDynamicFilename() && Const.isEmpty(meta.getDynamicFieldname())) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.DynamicFilenameFielddEmpty")); } // Check Attached zipfilename when dynamic if (meta.isZipFilenameDynamic() && Const.isEmpty(meta.getDynamicZipFilenameField())) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.DynamicZipFilenameFieldEmpty")); } if (meta.isZipFiles() && Const.isEmpty(meta.getZipFilename())) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.ZipFilenameEmpty")); } // check authentication if (meta.isUsingAuthentication()) { // check authentication user if (Const.isEmpty(meta.getAuthenticationUser())) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Log.AuthenticationUserFieldEmpty")); } // check authentication pass if (Const.isEmpty(meta.getAuthenticationPassword())) { throw new KettleException( BaseMessages.getString(PKG, "Mail.Log.AuthenticationPasswordFieldEmpty")); } } // cache the position of the destination field if (data.indexOfDestination < 0) { String realDestinationFieldname = meta.getDestination(); data.indexOfDestination = data.previousRowMeta.indexOfValue(realDestinationFieldname); if (data.indexOfDestination < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindDestinationField", realDestinationFieldname)); } } // Cc if (!Const.isEmpty(meta.getDestinationCc())) { // cache the position of the Cc field if (data.indexOfDestinationCc < 0) { String realDestinationCcFieldname = meta.getDestinationCc(); data.indexOfDestinationCc = data.previousRowMeta.indexOfValue(realDestinationCcFieldname); if (data.indexOfDestinationCc < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindDestinationCcField", realDestinationCcFieldname)); } } } // BCc if (!Const.isEmpty(meta.getDestinationBCc())) { // cache the position of the BCc field if (data.indexOfDestinationBCc < 0) { String realDestinationBCcFieldname = meta.getDestinationBCc(); data.indexOfDestinationBCc = data.previousRowMeta.indexOfValue(realDestinationBCcFieldname); if (data.indexOfDestinationBCc < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindDestinationBCcField", realDestinationBCcFieldname)); } } } // Sender Name if (!Const.isEmpty(meta.getReplyName())) { // cache the position of the sender field if (data.indexOfSenderName < 0) { String realSenderName = meta.getReplyName(); data.indexOfSenderName = data.previousRowMeta.indexOfValue(realSenderName); if (data.indexOfSenderName < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindReplyNameField", realSenderName)); } } } // Sender address // cache the position of the sender field if (data.indexOfSenderAddress < 0) { String realSenderAddress = meta.getReplyAddress(); data.indexOfSenderAddress = data.previousRowMeta.indexOfValue(realSenderAddress); if (data.indexOfSenderAddress < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindReplyAddressField", realSenderAddress)); } } // Reply to if (!Const.isEmpty(meta.getReplyToAddresses())) { // cache the position of the reply to field if (data.indexOfReplyToAddresses < 0) { String realReplyToAddresses = meta.getReplyToAddresses(); data.indexOfReplyToAddresses = data.previousRowMeta.indexOfValue(realReplyToAddresses); if (data.indexOfReplyToAddresses < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindReplyToAddressesField", realReplyToAddresses)); } } } // Contact Person if (!Const.isEmpty(meta.getContactPerson())) { // cache the position of the destination field if (data.indexOfContactPerson < 0) { String realContactPerson = meta.getContactPerson(); data.indexOfContactPerson = data.previousRowMeta.indexOfValue(realContactPerson); if (data.indexOfContactPerson < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindContactPersonField", realContactPerson)); } } } // Contact Phone if (!Const.isEmpty(meta.getContactPhone())) { // cache the position of the destination field if (data.indexOfContactPhone < 0) { String realContactPhone = meta.getContactPhone(); data.indexOfContactPhone = data.previousRowMeta.indexOfValue(realContactPhone); if (data.indexOfContactPhone < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindContactPhoneField", realContactPhone)); } } } // cache the position of the Server field if (data.indexOfServer < 0) { String realServer = meta.getServer(); data.indexOfServer = data.previousRowMeta.indexOfValue(realServer); if (data.indexOfServer < 0) { throw new KettleException( BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindServerField", realServer)); } } // Port if (!Const.isEmpty(meta.getPort())) { // cache the position of the port field if (data.indexOfPort < 0) { String realPort = meta.getPort(); data.indexOfPort = data.previousRowMeta.indexOfValue(realPort); if (data.indexOfPort < 0) { throw new KettleException( BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindPortField", realPort)); } } } // Authentication if (meta.isUsingAuthentication()) { // cache the position of the Authentication user field if (data.indexOfAuthenticationUser < 0) { String realAuthenticationUser = meta.getAuthenticationUser(); data.indexOfAuthenticationUser = data.previousRowMeta.indexOfValue(realAuthenticationUser); if (data.indexOfAuthenticationUser < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindAuthenticationUserField", realAuthenticationUser)); } } // cache the position of the Authentication password field if (data.indexOfAuthenticationPass < 0) { String realAuthenticationPassword = meta.getAuthenticationPassword(); data.indexOfAuthenticationPass = data.previousRowMeta.indexOfValue(realAuthenticationPassword); if (data.indexOfAuthenticationPass < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindAuthenticationPassField", realAuthenticationPassword)); } } } // Mail Subject if (!Const.isEmpty(meta.getSubject())) { // cache the position of the subject field if (data.indexOfSubject < 0) { String realSubject = meta.getSubject(); data.indexOfSubject = data.previousRowMeta.indexOfValue(realSubject); if (data.indexOfSubject < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindSubjectField", realSubject)); } } } // Mail Comment if (!Const.isEmpty(meta.getComment())) { // cache the position of the comment field if (data.indexOfComment < 0) { String realComment = meta.getComment(); data.indexOfComment = data.previousRowMeta.indexOfValue(realComment); if (data.indexOfComment < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindCommentField", realComment)); } } } if (meta.isAttachContentFromField()) { // We are dealing with file content directly loaded from file // and not physical file String attachedContentField = meta.getAttachContentField(); if (Const.isEmpty(attachedContentField)) { // Empty Field throw new KettleException( BaseMessages.getString(PKG, "Mail.Exception.AttachedContentFieldEmpty")); } data.indexOfAttachedContent = data.previousRowMeta.indexOfValue(attachedContentField); if (data.indexOfComment < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindAttachedContentField", attachedContentField)); } // Attached content filename String attachedContentFileNameField = meta.getAttachContentFileNameField(); if (Const.isEmpty(attachedContentFileNameField)) { // Empty Field throw new KettleException( BaseMessages.getString(PKG, "Mail.Exception.AttachedContentFileNameFieldEmpty")); } data.IndexOfAttachedFilename = data.previousRowMeta.indexOfValue(attachedContentFileNameField); if (data.indexOfComment < 0) { throw new KettleException( BaseMessages.getString(PKG, "Mail.Exception.CouldnotFindAttachedContentFileNameField", attachedContentFileNameField)); } } else { // Dynamic Zipfilename if (meta.isZipFilenameDynamic()) { // cache the position of the attached source filename field if (data.indexOfDynamicZipFilename < 0) { String realZipFilename = meta.getDynamicZipFilenameField(); data.indexOfDynamicZipFilename = data.previousRowMeta.indexOfValue(realZipFilename); if (data.indexOfDynamicZipFilename < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotSourceAttachedZipFilenameField", realZipFilename)); } } } data.zipFileLimit = Const.toLong(environmentSubstitute(meta.getZipLimitSize()), 0); if (data.zipFileLimit > 0) { data.zipFileLimit = data.zipFileLimit * 1048576; // Mo } if (!meta.isZipFilenameDynamic()) { data.ZipFilename = environmentSubstitute(meta.getZipFilename()); } // Attached files if (meta.isDynamicFilename()) { // cache the position of the attached source filename field if (data.indexOfSourceFilename < 0) { String realSourceattachedFilename = meta.getDynamicFieldname(); data.indexOfSourceFilename = data.previousRowMeta.indexOfValue(realSourceattachedFilename); if (data.indexOfSourceFilename < 0) { throw new KettleException(BaseMessages.getString(PKG, "Mail.Exception.CouldnotSourceAttachedFilenameField", realSourceattachedFilename)); } } // cache the position of the attached wildcard field if (!Const.isEmpty(meta.getSourceWildcard())) { if (data.indexOfSourceWildcard < 0) { String realSourceattachedWildcard = meta.getDynamicWildcard(); data.indexOfSourceWildcard = data.previousRowMeta .indexOfValue(realSourceattachedWildcard); if (data.indexOfSourceWildcard < 0) { throw new KettleException( BaseMessages.getString(PKG, "Mail.Exception.CouldnotSourceAttachedWildcard", realSourceattachedWildcard)); } } } } else { // static attached filenames data.realSourceFileFoldername = environmentSubstitute(meta.getSourceFileFoldername()); data.realSourceWildcard = environmentSubstitute(meta.getSourceWildcard()); } } // check embedded images if (meta.getEmbeddedImages() != null && meta.getEmbeddedImages().length > 0) { FileObject image = null; data.embeddedMimePart = new HashSet<MimeBodyPart>(); try { for (int i = 0; i < meta.getEmbeddedImages().length; i++) { String imageFile = environmentSubstitute(meta.getEmbeddedImages()[i]); String contentID = environmentSubstitute(meta.getContentIds()[i]); image = KettleVFS.getFileObject(imageFile); if (image.exists() && image.getType() == FileType.FILE) { // Create part for the image MimeBodyPart imagePart = new MimeBodyPart(); // Load the image URLDataSource fds = new URLDataSource(image.getURL()); imagePart.setDataHandler(new DataHandler(fds)); // Setting the header imagePart.setHeader("Content-ID", "<" + contentID + ">"); // keep this part for further user data.embeddedMimePart.add(imagePart); logBasic(BaseMessages.getString(PKG, "Mail.Log.ImageAdded", imageFile)); } else { logError(BaseMessages.getString(PKG, "Mail.Log.WrongImage", imageFile)); } } } catch (Exception e) { logError(BaseMessages.getString(PKG, "Mail.Error.AddingImage", e.getMessage())); } finally { if (image != null) { try { image.close(); } catch (Exception e) { /* Ignore */ } } } } } // end if first boolean sendToErrorRow = false; String errorMessage = null; try { // get values String maildestination = data.previousRowMeta.getString(r, data.indexOfDestination); if (Const.isEmpty(maildestination)) { throw new KettleException("Mail.Error.MailDestinationEmpty"); } String maildestinationCc = null; if (data.indexOfDestinationCc > -1) { maildestinationCc = data.previousRowMeta.getString(r, data.indexOfDestinationCc); } String maildestinationBCc = null; if (data.indexOfDestinationBCc > -1) { maildestinationBCc = data.previousRowMeta.getString(r, data.indexOfDestinationBCc); } String mailsendername = null; if (data.indexOfSenderName > -1) { mailsendername = data.previousRowMeta.getString(r, data.indexOfSenderName); } String mailsenderaddress = data.previousRowMeta.getString(r, data.indexOfSenderAddress); // reply addresses String mailreplyToAddresses = null; if (data.indexOfReplyToAddresses > -1) { mailreplyToAddresses = data.previousRowMeta.getString(r, data.indexOfReplyToAddresses); } String contactperson = null; if (data.indexOfContactPerson > -1) { contactperson = data.previousRowMeta.getString(r, data.indexOfContactPerson); } String contactphone = null; if (data.indexOfContactPhone > -1) { contactphone = data.previousRowMeta.getString(r, data.indexOfContactPhone); } String servername = data.previousRowMeta.getString(r, data.indexOfServer); if (Const.isEmpty(servername)) { throw new KettleException("Mail.Error.MailServerEmpty"); } int port = -1; if (data.indexOfPort > -1) { port = Const.toInt("" + data.previousRowMeta.getInteger(r, data.indexOfPort), -1); } String authuser = null; if (data.indexOfAuthenticationUser > -1) { authuser = data.previousRowMeta.getString(r, data.indexOfAuthenticationUser); } String authpass = null; if (data.indexOfAuthenticationPass > -1) { authpass = data.previousRowMeta.getString(r, data.indexOfAuthenticationPass); } String subject = null; if (data.indexOfSubject > -1) { subject = data.previousRowMeta.getString(r, data.indexOfSubject); } String comment = null; if (data.indexOfComment > -1) { comment = data.previousRowMeta.getString(r, data.indexOfComment); } // send email... sendMail(r, servername, port, mailsenderaddress, mailsendername, maildestination, maildestinationCc, maildestinationBCc, contactperson, contactphone, authuser, authpass, subject, comment, mailreplyToAddresses); putRow(getInputRowMeta(), r); // copy row to possible alternate rowset(s).); // copy row to output rowset(s); if (log.isRowLevel()) { logRowlevel(BaseMessages.getString(PKG, "Mail.Log.LineNumber", getLinesRead() + " : " + getInputRowMeta().getString(r))); } } catch (Exception e) { if (getStepMeta().isDoingErrorHandling()) { sendToErrorRow = true; errorMessage = e.toString(); } else { throw new KettleException(BaseMessages.getString(PKG, "Mail.Error.General"), e); } if (sendToErrorRow) { // Simply add this row to the error row putError(getInputRowMeta(), r, 1, errorMessage, null, "MAIL001"); } } return true; }
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 * //w w w .j a v a 2s. c o m * @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:org.sakaiproject.email.impl.BasicEmailService.java
/** * Attaches a file as a body part to the multipart message * * @param attachment// w ww . j a v a 2 s. com * @throws MessagingException */ private MimeBodyPart createAttachmentPart(Attachment attachment) throws MessagingException { DataSource source = attachment.getDataSource(); MimeBodyPart attachPart = new MimeBodyPart(); attachPart.setDataHandler(new DataHandler(source)); attachPart.setFileName(attachment.getFilename()); if (attachment.getContentTypeHeader() != null) { attachPart.setHeader("Content-Type", attachment.getContentTypeHeader()); } if (attachment.getContentDispositionHeader() != null) { attachPart.setHeader("Content-Disposition", attachment.getContentDispositionHeader()); } return attachPart; }
From source file:org.etudes.jforum.util.mail.Spammer.java
/** * prepare attachment message//from ww w . ja va2s . c om * @param addresses Addresses * @param params Message params * @param subject Message subject * @param messageFile Message file * @param attachments Attachments * @throws EmailException */ protected final void prepareAttachmentMessage(List addresses, SimpleHash params, String subject, String messageFile, List attachments) throws EmailException { if (logger.isDebugEnabled()) logger.debug("prepareAttachmentMessage with attachments entering....."); this.message = new MimeMessage(session); try { InternetAddress[] recipients = new InternetAddress[addresses.size()]; String charset = SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET); this.message.setSentDate(new Date()); // this.message.setFrom(new InternetAddress(SystemGlobals.getValue(ConfigKeys.MAIL_SENDER))); String from = "\"" + ServerConfigurationService.getString("ui.service", "Sakai") + "\"<no-reply@" + ServerConfigurationService.getServerName() + ">"; this.message.setFrom(new InternetAddress(from)); this.message.setSubject(subject, charset); this.messageText = this.getMessageText(params, messageFile); MimeBodyPart messageBodyPart = new MimeBodyPart(); String messagetype = ""; // message if (messageFormat == MESSAGE_HTML) { messagetype = "text/html; charset=" + charset; messageBodyPart.setContent(this.messageText, messagetype); } else { messagetype = "text/plain; charset=" + charset; messageBodyPart.setContent(this.messageText, messagetype); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // attachments Attachment attachment = null; Iterator iterAttach = attachments.iterator(); while (iterAttach.hasNext()) { attachment = (Attachment) iterAttach.next(); // String filePath = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + attachment.getInfo().getPhysicalFilename(); String filePath = SakaiSystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + attachment.getInfo().getPhysicalFilename(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filePath); try { messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getInfo().getRealFilename()); multipart.addBodyPart(messageBodyPart); } catch (MessagingException e) { if (logger.isWarnEnabled()) logger.warn("Error while attaching attachments in prepareAttachmentMessage(...) : " + e); } } message.setContent(multipart); int i = 0; for (Iterator iter = addresses.iterator(); iter.hasNext(); i++) { recipients[i] = new InternetAddress((String) iter.next()); } this.message.setRecipients(Message.RecipientType.TO, recipients); } catch (Exception e) { logger.warn(e); throw new EmailException(e); } if (logger.isDebugEnabled()) logger.debug("prepareAttachmentMessage with attachments exiting....."); }