001    package de.deepamehta.plugins.mail;
002    
003    import java.io.IOException;
004    import java.net.URL;
005    import java.util.logging.Logger;
006    
007    import org.apache.commons.mail.EmailException;
008    import org.apache.commons.mail.HtmlEmail;
009    import org.jsoup.Jsoup;
010    import org.jsoup.nodes.Document;
011    import org.jsoup.nodes.Element;
012    
013    import de.deepamehta.plugins.files.service.FilesService;
014    
015    class ImageCidEmbedment {
016    
017        private static Logger log = Logger.getLogger(MailPlugin.class.getName());
018    
019        private final FilesService fileService;
020    
021        public ImageCidEmbedment(FilesService fileService) {
022            this.fileService = fileService;
023        }
024    
025        /**
026         * Embed all images of body.
027         * 
028         * @return Document with CID replaced image source attributes.
029         */
030        public Document embedImages(HtmlEmail email, String body) throws EmailException, IOException {
031            int count = 0;
032            Document document = Jsoup.parse(body);
033            for (Element image : document.getElementsByTag("img")) {
034                URL url = new URL(image.attr("src"));
035                image.attr("src", "cid:" + embedImage(email, url, ++count + url.getPath()));
036            }
037            return document;
038        }
039    
040        /**
041         * Embed any image type (external URL, file repository and plugin resource).
042         * 
043         * @return CID of embedded image.
044         * @throws EmailException
045         */
046        public String embedImage(HtmlEmail email, URL url, String name) throws EmailException {
047            String path = fileService.getRepositoryPath(url);
048            if (path != null) { // repository link
049                log.fine("embed repository image " + path);
050                return email.embed(fileService.getFile(path));
051            } else { // external URL
052                log.fine("embed external image " + url);
053                return email.embed(url, name);
054            }
055        }
056    
057    }