List of usage examples for javax.activation URLDataSource URLDataSource
public URLDataSource(URL url)
From source file:lucee.runtime.net.mail.HtmlEmailImpl.java
/** * Embeds an URL in the HTML./*from w ww . j a va 2 s .c o m*/ * * <p>This method allows to embed a file located by an URL into * the mail body. It allows, for instance, to add inline images * to the email. Inline files may be referenced with a * <code>cid:xxxxxx</code> URL, where xxxxxx is the Content-ID * returned by the embed function. * * <p>Example of use:<br><code><pre> * HtmlEmail he = new HtmlEmail(); * he.setHtmlMsg("<html><img src=cid:" + * embed("file:/my/image.gif","image.gif") + * "></html>"); * // code to set the others email fields (not shown) * </pre></code> * * @param url The URL of the file. * @param cid A String with the Content-ID of the file. * @param name The name that will be set in the filename header * field. * @throws EmailException when URL supplied is invalid * also see javax.mail.internet.MimeBodyPart for definitions * */ public void embed(URL url, String cid, String name) throws EmailException { // verify that the URL is valid try { InputStream is = url.openStream(); is.close(); } catch (IOException e) { throw new EmailException("Invalid URL"); } MimeBodyPart mbp = new MimeBodyPart(); try { mbp.setDataHandler(new DataHandler(new URLDataSource(url))); mbp.setFileName(name); mbp.setDisposition("inline"); mbp.addHeader("Content-ID", "<" + cid + ">"); this.inlineImages.add(mbp); } catch (MessagingException me) { throw new EmailException(me); } }
From source file:com.aurel.track.util.emailHandling.MailBuilder.java
private void includeImageLogo(MimeMultipart mimeMultipart) { BodyPart messageBodyPart;/*from w ww.j a v a 2 s .co m*/ ArrayList<String> imageFiles = new ArrayList<String>(); imageFiles.add("tracklogo.gif"); // more images can be added here ArrayList<String> cids = new ArrayList<String>(); cids.add("logo"); // for each image there should be a cid here URL imageURL = null; for (int i = 0; i < imageFiles.size(); ++i) { try { DataSource ds = null; messageBodyPart = new MimeBodyPart(); InputStream in = null; in = ImageAction.class.getClassLoader().getResourceAsStream(imageFiles.get(i)); int length = imageFiles.get(i).length(); String type = imageFiles.get(i).substring(length - 4, length - 1); if (in != null) { ds = new ByteArrayDataSource(in, "image/" + type); System.err.println(type); } else { String theResource = "/WEB-INF/classes/resources/MailTemplates/" + imageFiles.get(i); imageURL = servletContext.getResource(theResource); ds = new URLDataSource(imageURL); } messageBodyPart.setDataHandler(new DataHandler(ds)); messageBodyPart.setHeader("Content-ID", cids.get(i)); messageBodyPart.setDisposition("inline"); // add it mimeMultipart.addBodyPart(messageBodyPart); } catch (Exception e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); // what shall we do here? } } }
From source file:com.zxy.commons.email.MailMessageUtils.java
/** * smtp??//from w w w. j a v a2 s .c om * * @param subject subject * @param htmlBody htmlBody * @param properties properties * @param from from * @param toList toList * @param ccList ccList * @param bccList bccList * @param embedUrls * @throws EmailException EmailException */ @SuppressWarnings({ "PMD.AvoidInstantiatingObjectsInLoops", "PMD.UseStringBufferForStringAppends" }) public static void sendMail(String subject, String htmlBody, Map<String, String> properties, String from, List<String> toList, List<String> ccList, List<String> bccList, Map<String, URL> embedUrls) throws EmailException { HtmlEmail htmlEmail = getEmail(); // from? if (!Strings.isNullOrEmpty(from)) { Address fromMailbox = parseMailbox(from); if (fromMailbox != null && StringUtils.isNotBlank(from)) { htmlEmail.setFrom(fromMailbox.getAddress(), fromMailbox.getName()); } } // to? if (toList != null && !toList.isEmpty()) { for (String to : toList) { if (StringUtils.isNotBlank(to)) { Address toMailbox = parseMailbox(to); htmlEmail.addTo(toMailbox.getAddress(), toMailbox.getName()); } } } // cc? if (ccList != null && !ccList.isEmpty()) { for (String cc : ccList) { if (StringUtils.isNotBlank(cc)) { Address ccMailbox = parseMailbox(cc); htmlEmail.addCc(ccMailbox.getAddress(), ccMailbox.getName()); } } } // bcc? if (bccList != null && !bccList.isEmpty()) { for (String bcc : bccList) { if (StringUtils.isNotBlank(bcc)) { Address bccMailbox = parseMailbox(bcc); htmlEmail.addBcc(bccMailbox.getAddress(), bccMailbox.getName()); } } } // htmlEmail.setSubject(subject); htmlEmail.setHtmlMsg(htmlBody); htmlEmail.setSentDate(new Date()); // if (properties != null) { htmlEmail.setHeaders(properties); } // if (embedUrls != null && !embedUrls.isEmpty()) { for (Map.Entry<String, URL> entry : embedUrls.entrySet()) { String cid = entry.getKey(); URL url = entry.getValue(); String fileName = StringUtils.substringAfterLast(url.getPath(), "/"); if (StringUtils.isBlank(fileName)) { fileName = cid; } else { fileName += IdUtils.genStringId(); } htmlEmail.embed(new URLDataSource(url), fileName, cid); } } htmlEmail.send(); }
From source file:io.mapzone.arena.share.app.EMailSharelet.java
private void sendEmail(final String toText, final String subjectText, final String messageText, final boolean withAttachment, final ImagePngContent image) throws Exception { MimeMessage msg = new MimeMessage(mailSession()); msg.addRecipients(RecipientType.TO, InternetAddress.parse(toText, false)); // TODO we need the FROM from the current user msg.addFrom(InternetAddress.parse("support@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setReplyTo(InternetAddress.parse("DO_NOT_REPLY_TO_THIS_EMAIL@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setSubject(subjectText, "utf-8"); if (withAttachment) { // add mime multiparts Multipart multipart = new MimeMultipart(); BodyPart part = new MimeBodyPart(); part.setText(messageText);/*w w w. ja v a2 s . co m*/ multipart.addBodyPart(part); // Second part is attachment part = new MimeBodyPart(); part.setDataHandler(new DataHandler(new URLDataSource(new URL(image.imgResource)))); part.setFileName("preview.png"); part.setHeader("Content-ID", "preview"); multipart.addBodyPart(part); // // third part in HTML with embedded image // part = new MimeBodyPart(); // part.setContent( "<img src='cid:preview'>", "text/html" ); // multipart.addBodyPart( part ); msg.setContent(multipart); } else { msg.setText(messageText, "utf-8"); } msg.setSentDate(new Date()); Transport.send(msg); }
From source file:immf.MyHtmlEmail.java
/** * Embeds an URL in the HTML.//from w ww. j av a2s. c o m * * <p>This method embeds a file located by an URL into * the mail body. It allows, for instance, to add inline images * to the email. Inline files may be referenced with a * <code>cid:xxxxxx</code> URL, where xxxxxx is the Content-ID * returned by the embed function. It is an error to bind the same name * to more than one URL; if the same URL is embedded multiple times, the * same Content-ID is guaranteed to be returned. * * <p>While functionally the same as passing <code>URLDataSource</code> to * {@link #embed(DataSource, String, String)}, this method attempts * to validate the URL before embedding it in the message and will throw * <code>EmailException</code> if the validation fails. In this case, the * <code>HtmlEmail</code> object will not be changed. * * <p> * NOTE: Clients should take care to ensure that different URLs are bound to * different names. This implementation tries to detect this and throw * <code>EmailException</code>. However, it is not guaranteed to catch * all cases, especially when the URL refers to a remote HTTP host that * may be part of a virtual host cluster. * * @param url The URL of the file. * @param name The name that will be set in the filename header * field. * @return A String with the Content-ID of the file. * @throws EmailException when URL supplied is invalid or if <code> is null * or empty; also see {@link javax.mail.internet.MimeBodyPart} for definitions * @since 1.0 */ public String embed(URL url, String name) throws EmailException { if (StringUtils.isEmpty(name)) { throw new EmailException("name cannot be null or empty"); } // check if a URLDataSource for this name has already been attached; // if so, return the cached CID value. if (inlineEmbeds.containsKey(name)) { InlineImage ii = (InlineImage) inlineEmbeds.get(name); URLDataSource urlDataSource = (URLDataSource) ii.getDataSource(); // make sure the supplied URL points to the same thing // as the one already associated with this name. // NOTE: Comparing URLs with URL.equals() is a blocking operation // in the case of a network failure therefore we use // url.toExternalForm().equals() here. if (url.toExternalForm().equals(urlDataSource.getURL().toExternalForm())) { return ii.getCid(); } else { throw new EmailException("embedded name '" + name + "' is already bound to URL " + urlDataSource.getURL() + "; existing names cannot be rebound"); } } // verify that the URL is valid InputStream is = null; try { is = url.openStream(); } catch (IOException e) { throw new EmailException("Invalid URL", e); } finally { try { if (is != null) { is.close(); } } catch (IOException ioe) { /* sigh */ } } return embed(new URLDataSource(url), name); }
From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java
public DataSource retrieveFSDesignResourceContent(RemoteSession session, FSDesignResourceState state) throws WGAServiceException { if (!isAdminServiceEnabled()) { throw new WGAServiceException("Administrative services are disabled"); }/*from w w w. j a v a 2 s . co m*/ if (!isAdminSession(session)) { throw new WGAServiceException("You need an administrative login to access this service."); } WGADesignSource source = _core.getDesignManager().getDesignSources() .get(WGAConfiguration.UID_DESIGNSOURCE_FILESYSTEM); if (source instanceof FileSystemDesignSource) { FileSystemDesignSource fsSource = (FileSystemDesignSource) source; try { fsSource.getDir().refresh(); FileObject resource = fsSource.getDir().resolveFile(state.getPath()); String basePath = fsSource.getDir().getURL().getPath(); String resourcePath = resource.getURL().getPath(); if (!resourcePath.startsWith(basePath)) { throw new WGAServiceException(new IllegalArgumentException( "Illegal design resource path '" + state.getPath() + "'.")); } if (resource.exists()) { if (resource.getType().equals(FileType.FOLDER)) { throw new WGAServiceException( new IllegalArgumentException("Cannot retrieve content of a folder.")); } else { return new URLDataSource(resource.getURL()); } } } catch (FileSystemException e) { throw new WGAServiceException( "Retrieving content of FSDesignResource '" + state.getPath() + "' failed.", e); } } return null; }
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 w w w .ja v a 2 s . co 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.youxifan.utils.EMail.java
/** * Set the message content/*from w w w. ja va 2 s.co m*/ * @throws MessagingException * @throws IOException */ private void setContent() throws MessagingException, IOException { // Local Character Set String charSetName; if (m_encoding == null) { charSetName = System.getProperty("file.encoding"); // Cp1252 if (charSetName == null || charSetName.length() == 0) charSetName = "UTF-8"; // WebEnv.ENCODING - alternative iso-8859-1 } else { charSetName = m_encoding; } m_msg.setSubject(getSubject(), charSetName); // Simple Message if (m_attachments == null || m_attachments.size() == 0) { if (m_messageHTML == null || m_messageHTML.length() == 0) m_msg.setText(getMessageCRLF(), charSetName); else m_msg.setDataHandler( new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html"))); // log.info("(simple) " + getSubject()); } else // Multi part message *************************************** { // First Part - Message MimeBodyPart mbp_1 = new MimeBodyPart(); mbp_1.setText(""); if (m_messageHTML == null || m_messageHTML.length() == 0) mbp_1.setText(getMessageCRLF(), charSetName); else mbp_1.setDataHandler( new DataHandler(new ByteArrayDataSource(m_messageHTML, charSetName, "text/html"))); // Create Multipart and its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp_1); log.info("(multi) " + getSubject() + " - " + mbp_1); // for all attachments for (int i = 0; i < m_attachments.size(); i++) { Object attachment = m_attachments.get(i); DataSource ds = null; if (attachment instanceof File) { File file = (File) attachment; if (file.exists()) ds = new FileDataSource(file); else { log.warn("File does not exist: " + file); continue; } } else if (attachment instanceof URL) { URL url = (URL) attachment; ds = new URLDataSource(url); } else if (attachment instanceof DataSource) ds = (DataSource) attachment; else { log.warn("Attachement type unknown: " + attachment); continue; } // Attachment Part MimeBodyPart mbp_2 = new MimeBodyPart(); mbp_2.setDataHandler(new DataHandler(ds)); mbp_2.setFileName(ds.getName()); log.info("Added Attachment " + ds.getName() + " - " + mbp_2); mp.addBodyPart(mbp_2); } // Add to Message m_msg.setContent(mp); } // multi=part }
From source file:com.panet.imeta.trans.steps.mail.Mail.java
private void addAttachedFilePart(FileObject file) throws Exception { // create a data source MimeBodyPart files = new MimeBodyPart(); // create a data source URLDataSource fds = new URLDataSource(file.getURL()); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(file.getName().getBaseName()); // add the part with the file in the BodyPart(); data.parts.addBodyPart(files);/*from w w w .j av a 2 s . c o m*/ if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("Mail.Log.AttachedFile", fds.getName())); }
From source file:com.panet.imeta.job.entries.mail.JobEntryMail.java
public Result execute(Result result, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); File masterZipfile = null;/*from w w w .ja v a2s . com*/ // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { log.logError(toString(), Messages.getString("JobMail.Error.HostNotSpecified")); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { if (secureConnectionType.equals("TLS")) { // Allow TLS authentication props.put("mail.smtp.starttls.enable", "true"); } else { protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version // Unknown props.put("mail.smtps.quitwait", "false"); } } props.put("mail." + protocol + ".host", environmentSubstitute(server)); if (!Const.isEmpty(port)) props.put("mail." + protocol + ".port", environmentSubstitute(port)); boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG; if (debug) props.put("mail.debug", "true"); if (usingAuthentication) { props.put("mail." + protocol + ".auth", "true"); /* * authenticator = new Authenticator() { protected * PasswordAuthentication getPasswordAuthentication() { return new * PasswordAuthentication( * StringUtil.environmentSubstitute(Const.NVL(authenticationUser, * "")), * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword * , "")) ); } }; */ } Session session = Session.getInstance(props); session.setDebug(debug); try { // create a message Message msg = new MimeMessage(session); // set message priority if (usePriority) { String priority_int = "1"; if (priority.equals("low")) { priority_int = "3"; } if (priority.equals("normal")) { priority_int = "2"; } msg.setHeader("X-Priority", priority_int); // (String)int // between 1= high // and 3 = low. msg.setHeader("Importance", importance); // seems to be needed for MS Outlook. // where it returns a string of high /normal /low. } // Set Mail sender (From) String sender_address = environmentSubstitute(replyAddress); if (!Const.isEmpty(sender_address)) { String sender_name = environmentSubstitute(replyName); if (!Const.isEmpty(sender_name)) sender_address = sender_name + '<' + sender_address + '>'; msg.setFrom(new InternetAddress(sender_address)); } else { throw new MessagingException(Messages.getString("JobMail.Error.ReplyEmailNotFilled")); } // set Reply to addresses String reply_to_address = environmentSubstitute(replyToAddresses); if (!Const.isEmpty(reply_to_address)) { // Split the mail-address: space separated String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) address[i] = new InternetAddress(reply_Address_List[i]); msg.setReplyTo(address); } // Split the mail-address: space separated String destinations[] = environmentSubstitute(destination).split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) address[i] = new InternetAddress(destinations[i]); msg.setRecipients(Message.RecipientType.TO, address); if (!Const.isEmpty(destinationCc)) { // Split the mail-address Cc: space separated String destinationsCc[] = environmentSubstitute(destinationCc).split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) addressCc[i] = new InternetAddress(destinationsCc[i]); msg.setRecipients(Message.RecipientType.CC, addressCc); } if (!Const.isEmpty(destinationBCc)) { // Split the mail-address BCc: space separated String destinationsBCc[] = environmentSubstitute(destinationBCc).split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) addressBCc[i] = new InternetAddress(destinationsBCc[i]); msg.setRecipients(Message.RecipientType.BCC, addressBCc); } String realSubject = environmentSubstitute(subject); if (!Const.isEmpty(realSubject)) { msg.setSubject(realSubject); } msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); if (comment != null) { messageText.append(environmentSubstitute(comment)).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append(Messages.getString("JobMail.Log.Comment.Job")).append(Const.CR); messageText.append("-----").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobName") + " : ") .append(parentJob.getJobMeta().getName()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobDirectory") + " : ") .append(parentJob.getJobMeta().getDirectory()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobEntry") + " : ").append(getName()) .append(Const.CR); messageText.append(Const.CR); } if (includeDate) { messageText.append(Const.CR).append(Messages.getString("JobMail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR); } if (!onlySendComment && result != null) { messageText.append(Messages.getString("JobMail.Log.Comment.PreviousResult") + ":").append(Const.CR); messageText.append("-----------------").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.JobEntryNr") + " : ") .append(result.getEntryNr()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Errors") + " : ") .append(result.getNrErrors()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesRead") + " : ") .append(result.getNrLinesRead()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesWritten") + " : ") .append(result.getNrLinesWritten()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesInput") + " : ") .append(result.getNrLinesInput()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesOutput") + " : ") .append(result.getNrLinesOutput()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.LinesUpdated") + " : ") .append(result.getNrLinesUpdated()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Status") + " : ") .append(result.getExitStatus()).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Result") + " : ") .append(result.getResult()).append(Const.CR); messageText.append(Const.CR); } if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson)) || !Const.isEmpty(environmentSubstitute(contactPhone)))) { messageText.append(Messages.getString("JobMail.Log.Comment.ContactInfo") + " :").append(Const.CR); messageText.append("---------------------").append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.PersonToContact") + " : ") .append(environmentSubstitute(contactPerson)).append(Const.CR); messageText.append(Messages.getString("JobMail.Log.Comment.Tel") + " : ") .append(environmentSubstitute(contactPhone)).append(Const.CR); messageText.append(Const.CR); } // Include the path to this job entry... if (!onlySendComment) { JobTracker jobTracker = parentJob.getJobTracker(); if (jobTracker != null) { messageText.append(Messages.getString("JobMail.Log.Comment.PathToJobentry") + ":") .append(Const.CR); messageText.append("------------------------").append(Const.CR); addBacktracking(jobTracker, messageText); } } Multipart parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // 1st part if (useHTML) { if (!Const.isEmpty(getEncoding())) { part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding()); } else { part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } } else part1.setText(messageText.toString()); parts.addBodyPart(part1); if (includingFiles && result != null) { List<ResultFile> resultFiles = result.getResultFilesList(); if (resultFiles != null && !resultFiles.isEmpty()) { if (!zipFiles) { // Add all files to the message... // for (ResultFile resultFile : resultFiles) { FileObject file = resultFile.getFile(); if (file != null && file.exists()) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { // create a data source MimeBodyPart files = new MimeBodyPart(); URLDataSource fds = new URLDataSource(file.getURL()); // get a data Handler to manipulate this // file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(file.getName().getBaseName()); // add the part with the file in the // BodyPart(); parts.addBodyPart(files); log.logBasic(toString(), "Added file '" + fds.getName() + "' to the mail message."); } } } } else { // create a single ZIP archive of all files masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (ResultFile resultFile : resultFiles) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) found = true; } if (found) { FileObject file = resultFile.getFile(); ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into // this archive... BufferedInputStream inputStream = new BufferedInputStream( KettleVFS.getInputStream(file)); int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } inputStream.close(); zipOutputStream.closeEntry(); log.logBasic(toString(), "Added file '" + file.getName().getURI() + "' to the mail message in a zip archive."); } } } catch (Exception e) { log.logError(toString(), "Error zipping attachement files into file [" + masterZipfile.getPath() + "] : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { log.logError(toString(), "Unable to close attachement zip file archive : " + e.toString()); log.logError(toString(), Const.getStackTracker(e)); result.setNrErrors(1); } } } // Now attach the master zip file to the message. if (result.getNrErrors() == 0) { // create a data source MimeBodyPart files = new MimeBodyPart(); FileDataSource fds = new FileDataSource(masterZipfile); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in th e data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); } } } } msg.setContent(parts); Transport transport = null; try { transport = session.getTransport(protocol); if (usingAuthentication) { if (!Const.isEmpty(port)) { transport.connect(environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))), environmentSubstitute(Const.NVL(authenticationUser, "")), environmentSubstitute(Const.NVL(authenticationPassword, ""))); } else { transport.connect(environmentSubstitute(Const.NVL(server, "")), environmentSubstitute(Const.NVL(authenticationUser, "")), environmentSubstitute(Const.NVL(authenticationPassword, ""))); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) transport.close(); } } catch (IOException e) { log.logError(toString(), "Problem while sending message: " + e.toString()); result.setNrErrors(1); } catch (MessagingException mex) { log.logError(toString(), "Problem while sending message: " + mex.toString()); result.setNrErrors(1); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { log.logError(toString(), " ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) { log.logError(toString(), " " + invalid[i]); result.setNrErrors(1); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { log.logError(toString(), " ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) { log.logError(toString(), " " + validUnsent[i]); result.setNrErrors(1); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { // System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) { log.logError(toString(), " " + validSent[i]); result.setNrErrors(1); } } } if (ex instanceof MessagingException) { ex = ((MessagingException) ex).getNextException(); } else { ex = null; } } while (ex != null); } finally { if (masterZipfile != null && masterZipfile.exists()) { masterZipfile.delete(); } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } return result; }