List of usage examples for javax.activation DataHandler DataHandler
public DataHandler(URL url)
DataHandler
instance referencing a URL. From source file:org.exist.xquery.modules.mail.SendEmailFunction.java
/** * Constructs a mail Object from an XML representation of an email * * The XML email Representation is expected to look something like this * * <mail>/*w w w .ja v a2 s.c o m*/ * <from></from> * <reply-to></reply-to> * <to></to> * <cc></cc> * <bcc></bcc> * <subject></subject> * <message> * <text charset="" encoding=""></text> * <xhtml charset="" encoding=""></xhtml> * <generic charset="" type="" encoding=""></generic> * </message> * <attachment mimetype="" filename=""></attachment> * </mail> * * @param mailElements The XML mail Node * @return A mail Object representing the XML mail Node */ private List<Message> parseMessageElement(Session session, List<Element> mailElements) throws IOException, MessagingException, TransformerException { List<Message> mails = new ArrayList<>(); for (Element mailElement : mailElements) { //Make sure that message has a Mail node if (mailElement.getLocalName().equals("mail")) { //New message Object // create a message MimeMessage msg = new MimeMessage(session); ArrayList<InternetAddress> replyTo = new ArrayList<>(); boolean fromWasSet = false; MimeBodyPart body = null; Multipart multibody = null; ArrayList<MimeBodyPart> attachments = new ArrayList<>(); String firstContent = null; String firstContentType = null; String firstCharset = null; String firstEncoding = null; //Get the First Child Node child = mailElement.getFirstChild(); while (child != null) { //Parse each of the child nodes if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) { switch (child.getLocalName()) { case "from": // set the from and to address InternetAddress[] addressFrom = { new InternetAddress(child.getFirstChild().getNodeValue()) }; msg.addFrom(addressFrom); fromWasSet = true; break; case "reply-to": // As we can only set the reply-to, not add them, let's keep // all of them in a list replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue())); msg.setReplyTo(replyTo.toArray(new InternetAddress[0])); break; case "to": msg.addRecipient(Message.RecipientType.TO, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "cc": msg.addRecipient(Message.RecipientType.CC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "bcc": msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(child.getFirstChild().getNodeValue())); break; case "subject": msg.setSubject(child.getFirstChild().getNodeValue()); break; case "header": // Optional : You can also set your custom headers in the Email if you Want msg.addHeader(((Element) child).getAttribute("name"), child.getFirstChild().getNodeValue()); break; case "message": //If the message node, then parse the child text and xhtml nodes Node bodyPart = child.getFirstChild(); while (bodyPart != null) { if (bodyPart.getNodeType() != Node.ELEMENT_NODE) continue; Element elementBodyPart = (Element) bodyPart; String content = null; String contentType = null; if (bodyPart.getLocalName().equals("text")) { // Setting the Subject and Content Type content = bodyPart.getFirstChild().getNodeValue(); contentType = "plain"; } else if (bodyPart.getLocalName().equals("xhtml")) { //Convert everything inside <xhtml></xhtml> to text TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(bodyPart.getFirstChild()); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content = strWriter.toString(); contentType = "html"; } else if (bodyPart.getLocalName().equals("generic")) { // Setting the Subject and Content Type content = elementBodyPart.getFirstChild().getNodeValue(); contentType = elementBodyPart.getAttribute("type"); } // Now, time to store it if (content != null && contentType != null && contentType.length() > 0) { String charset = elementBodyPart.getAttribute("charset"); String encoding = elementBodyPart.getAttribute("encoding"); if (body != null && multibody == null) { multibody = new MimeMultipart("alternative"); multibody.addBodyPart(body); } if (StringUtils.isEmpty(charset)) { charset = "UTF-8"; } if (StringUtils.isEmpty(encoding)) { encoding = "quoted-printable"; } if (body == null) { firstContent = content; firstCharset = charset; firstContentType = contentType; firstEncoding = encoding; } body = new MimeBodyPart(); body.setText(content, charset, contentType); if (encoding != null) { body.setHeader("Content-Transfer-Encoding", encoding); } if (multibody != null) multibody.addBodyPart(body); } //next body part bodyPart = bodyPart.getNextSibling(); } break; case "attachment": Element attachment = (Element) child; MimeBodyPart part; // if mimetype indicates a binary resource, assume the content is base64 encoded if (MimeTable.getInstance().isTextContent(attachment.getAttribute("mimetype"))) { part = new MimeBodyPart(); } else { part = new PreencodedMimeBodyPart("base64"); } StringBuilder content = new StringBuilder(); Node attachChild = attachment.getFirstChild(); while (attachChild != null) { if (attachChild.getNodeType() == Node.ELEMENT_NODE) { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); DOMSource source = new DOMSource(attachChild); StringWriter strWriter = new StringWriter(); StreamResult result = new StreamResult(strWriter); transformer.transform(source, result); content.append(strWriter.toString()); } else { content.append(attachChild.getNodeValue()); } attachChild = attachChild.getNextSibling(); } part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(), attachment.getAttribute("mimetype")))); part.setFileName(attachment.getAttribute("filename")); // part.setHeader("Content-Transfer-Encoding", "base64"); attachments.add(part); break; } } //next node child = child.getNextSibling(); } // Lost from if (!fromWasSet) msg.setFrom(); // Preparing content and attachments if (attachments.size() > 0) { if (multibody == null) { multibody = new MimeMultipart("mixed"); if (body != null) { multibody.addBodyPart(body); } } else { MimeMultipart container = new MimeMultipart("mixed"); MimeBodyPart containerBody = new MimeBodyPart(); containerBody.setContent(multibody); container.addBodyPart(containerBody); multibody = container; } for (MimeBodyPart part : attachments) { multibody.addBodyPart(part); } } // And now setting-up content if (multibody != null) { msg.setContent(multibody); } else if (body != null) { msg.setText(firstContent, firstCharset, firstContentType); if (firstEncoding != null) { msg.setHeader("Content-Transfer-Encoding", firstEncoding); } } msg.saveChanges(); mails.add(msg); } } return mails; }
From source file:org.pentaho.di.job.entries.mail.JobEntryMail.java
public Result execute(Result result, int nr) { File masterZipfile = null;// w w w . java2s . c o m // Send an e-mail... // create some properties and get the default Session Properties props = new Properties(); if (Const.isEmpty(server)) { logError(BaseMessages.getString(PKG, "JobMail.Error.HostNotSpecified")); result.setNrErrors(1L); result.setResult(false); return result; } String protocol = "smtp"; if (usingSecureAuthentication) { if (secureConnectionType.equals("TLS")) { // Allow TLS authentication props.put("mail.smtp.starttls.enable", "true"); } else { protocol = "smtps"; // required to get rid of a SSL exception : // nested exception is: // javax.net.ssl.SSLException: Unsupported record version Unknown props.put("mail.smtps.quitwait", "false"); } } props.put("mail." + protocol + ".host", environmentSubstitute(server)); if (!Const.isEmpty(port)) { props.put("mail." + protocol + ".port", environmentSubstitute(port)); } if (log.isDebug()) { props.put("mail.debug", "true"); } if (usingAuthentication) { props.put("mail." + protocol + ".auth", "true"); /* * authenticator = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new * PasswordAuthentication( StringUtil.environmentSubstitute(Const.NVL(authenticationUser, "")), * StringUtil.environmentSubstitute(Const.NVL(authenticationPassword, "")) ); } }; */ } Session session = Session.getInstance(props); session.setDebug(log.isDebug()); try { // create a message Message msg = new MimeMessage(session); // set message priority if (usePriority) { String priority_int = "1"; if (priority.equals("low")) { priority_int = "3"; } if (priority.equals("normal")) { priority_int = "2"; } msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low. msg.setHeader("Importance", importance); // seems to be needed for MS Outlook. // where it returns a string of high /normal /low. msg.setHeader("Sensitivity", sensitivity); // Possible values are normal, personal, private, company-confidential } // Set Mail sender (From) String sender_address = environmentSubstitute(replyAddress); if (!Const.isEmpty(sender_address)) { String sender_name = environmentSubstitute(replyName); if (!Const.isEmpty(sender_name)) { sender_address = sender_name + '<' + sender_address + '>'; } msg.setFrom(new InternetAddress(sender_address)); } else { throw new MessagingException(BaseMessages.getString(PKG, "JobMail.Error.ReplyEmailNotFilled")); } // set Reply to addresses String reply_to_address = environmentSubstitute(replyToAddresses); if (!Const.isEmpty(reply_to_address)) { // Split the mail-address: space separated String[] reply_Address_List = environmentSubstitute(reply_to_address).split(" "); InternetAddress[] address = new InternetAddress[reply_Address_List.length]; for (int i = 0; i < reply_Address_List.length; i++) { address[i] = new InternetAddress(reply_Address_List[i]); } msg.setReplyTo(address); } // Split the mail-address: space separated String[] destinations = environmentSubstitute(destination).split(" "); InternetAddress[] address = new InternetAddress[destinations.length]; for (int i = 0; i < destinations.length; i++) { address[i] = new InternetAddress(destinations[i]); } msg.setRecipients(Message.RecipientType.TO, address); String realCC = environmentSubstitute(getDestinationCc()); if (!Const.isEmpty(realCC)) { // Split the mail-address Cc: space separated String[] destinationsCc = realCC.split(" "); InternetAddress[] addressCc = new InternetAddress[destinationsCc.length]; for (int i = 0; i < destinationsCc.length; i++) { addressCc[i] = new InternetAddress(destinationsCc[i]); } msg.setRecipients(Message.RecipientType.CC, addressCc); } String realBCc = environmentSubstitute(getDestinationBCc()); if (!Const.isEmpty(realBCc)) { // Split the mail-address BCc: space separated String[] destinationsBCc = realBCc.split(" "); InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length]; for (int i = 0; i < destinationsBCc.length; i++) { addressBCc[i] = new InternetAddress(destinationsBCc[i]); } msg.setRecipients(Message.RecipientType.BCC, addressBCc); } String realSubject = environmentSubstitute(subject); if (!Const.isEmpty(realSubject)) { msg.setSubject(realSubject); } msg.setSentDate(new Date()); StringBuffer messageText = new StringBuffer(); String endRow = isUseHTML() ? "<br>" : Const.CR; String realComment = environmentSubstitute(comment); if (!Const.isEmpty(realComment)) { messageText.append(realComment).append(Const.CR).append(Const.CR); } if (!onlySendComment) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Job")).append(endRow); messageText.append("-----").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobName") + " : ") .append(parentJob.getJobMeta().getName()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobDirectory") + " : ") .append(parentJob.getJobMeta().getRepositoryDirectory()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntry") + " : ") .append(getName()).append(endRow); messageText.append(Const.CR); } if (includeDate) { messageText.append(endRow).append(BaseMessages.getString(PKG, "JobMail.Log.Comment.MsgDate") + ": ") .append(XMLHandler.date2string(new Date())).append(endRow).append(endRow); } if (!onlySendComment && result != null) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PreviousResult") + ":") .append(endRow); messageText.append("-----------------").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.JobEntryNr") + " : ") .append(result.getEntryNr()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Errors") + " : ") .append(result.getNrErrors()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRead") + " : ") .append(result.getNrLinesRead()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesWritten") + " : ") .append(result.getNrLinesWritten()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesInput") + " : ") .append(result.getNrLinesInput()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesOutput") + " : ") .append(result.getNrLinesOutput()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesUpdated") + " : ") .append(result.getNrLinesUpdated()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.LinesRejected") + " : ") .append(result.getNrLinesRejected()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Status") + " : ") .append(result.getExitStatus()).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Result") + " : ") .append(result.getResult()).append(endRow); messageText.append(endRow); } if (!onlySendComment && (!Const.isEmpty(environmentSubstitute(contactPerson)) || !Const.isEmpty(environmentSubstitute(contactPhone)))) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.ContactInfo") + " :") .append(endRow); messageText.append("---------------------").append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PersonToContact") + " : ") .append(environmentSubstitute(contactPerson)).append(endRow); messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.Tel") + " : ") .append(environmentSubstitute(contactPhone)).append(endRow); messageText.append(endRow); } // Include the path to this job entry... if (!onlySendComment) { JobTracker jobTracker = parentJob.getJobTracker(); if (jobTracker != null) { messageText.append(BaseMessages.getString(PKG, "JobMail.Log.Comment.PathToJobentry") + ":") .append(endRow); messageText.append("------------------------").append(endRow); addBacktracking(jobTracker, messageText); if (isUseHTML()) { messageText.replace(0, messageText.length(), messageText.toString().replace(Const.CR, endRow)); } } } MimeMultipart parts = new MimeMultipart(); MimeBodyPart part1 = new MimeBodyPart(); // put the text in the // Attached files counter int nrattachedFiles = 0; // 1st part if (useHTML) { if (!Const.isEmpty(getEncoding())) { part1.setContent(messageText.toString(), "text/html; " + "charset=" + getEncoding()); } else { part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1"); } } else { part1.setText(messageText.toString()); } parts.addBodyPart(part1); if (includingFiles && result != null) { List<ResultFile> resultFiles = result.getResultFilesList(); if (resultFiles != null && !resultFiles.isEmpty()) { if (!zipFiles) { // Add all files to the message... // for (ResultFile resultFile : resultFiles) { FileObject file = resultFile.getFile(); if (file != null && file.exists()) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) { found = true; } } if (found) { // create a data source MimeBodyPart files = new MimeBodyPart(); URLDataSource fds = new URLDataSource(file.getURL()); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(file.getName().getBaseName()); // insist on base64 to preserve line endings files.addHeader("Content-Transfer-Encoding", "base64"); // add the part with the file in the BodyPart(); parts.addBodyPart(files); nrattachedFiles++; logBasic("Added file '" + fds.getName() + "' to the mail message."); } } } } else { // create a single ZIP archive of all files masterZipfile = new File(System.getProperty("java.io.tmpdir") + Const.FILE_SEPARATOR + environmentSubstitute(zipFilename)); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(masterZipfile)); for (ResultFile resultFile : resultFiles) { boolean found = false; for (int i = 0; i < fileType.length; i++) { if (fileType[i] == resultFile.getType()) { found = true; } } if (found) { FileObject file = resultFile.getFile(); ZipEntry zipEntry = new ZipEntry(file.getName().getBaseName()); zipOutputStream.putNextEntry(zipEntry); // Now put the content of this file into this archive... BufferedInputStream inputStream = new BufferedInputStream( KettleVFS.getInputStream(file)); try { int c; while ((c = inputStream.read()) >= 0) { zipOutputStream.write(c); } } finally { inputStream.close(); } zipOutputStream.closeEntry(); nrattachedFiles++; logBasic("Added file '" + file.getName().getURI() + "' to the mail message in a zip archive."); } } } catch (Exception e) { logError("Error zipping attachement files into file [" + masterZipfile.getPath() + "] : " + e.toString()); logError(Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (zipOutputStream != null) { try { zipOutputStream.finish(); zipOutputStream.close(); } catch (IOException e) { logError("Unable to close attachement zip file archive : " + e.toString()); logError(Const.getStackTracker(e)); result.setNrErrors(1); } } } // Now attach the master zip file to the message. if (result.getNrErrors() == 0) { // create a data source MimeBodyPart files = new MimeBodyPart(); FileDataSource fds = new FileDataSource(masterZipfile); // get a data Handler to manipulate this file type; files.setDataHandler(new DataHandler(fds)); // include the file in the data source files.setFileName(fds.getName()); // add the part with the file in the BodyPart(); parts.addBodyPart(files); } } } } int nrEmbeddedImages = 0; if (embeddedimages != null && embeddedimages.length > 0) { FileObject imageFile = null; for (int i = 0; i < embeddedimages.length; i++) { String realImageFile = environmentSubstitute(embeddedimages[i]); String realcontenID = environmentSubstitute(contentids[i]); if (messageText.indexOf("cid:" + realcontenID) < 0) { if (log.isDebug()) { log.logDebug("Image [" + realImageFile + "] is not used in message body!"); } } else { try { boolean found = false; imageFile = KettleVFS.getFileObject(realImageFile, this); if (imageFile.exists() && imageFile.getType() == FileType.FILE) { found = true; } else { log.logError("We can not find [" + realImageFile + "] or it is not a file"); } if (found) { // Create part for the image MimeBodyPart messageBodyPart = new MimeBodyPart(); // Load the image URLDataSource fds = new URLDataSource(imageFile.getURL()); messageBodyPart.setDataHandler(new DataHandler(fds)); // Setting the header messageBodyPart.setHeader("Content-ID", "<" + realcontenID + ">"); // Add part to multi-part parts.addBodyPart(messageBodyPart); nrEmbeddedImages++; log.logBasic("Image '" + fds.getName() + "' was embedded in message."); } } catch (Exception e) { log.logError( "Error embedding image [" + realImageFile + "] in message : " + e.toString()); log.logError(Const.getStackTracker(e)); result.setNrErrors(1); } finally { if (imageFile != null) { try { imageFile.close(); } catch (Exception e) { /* Ignore */ } } } } } } if (nrEmbeddedImages > 0 && nrattachedFiles == 0) { // If we need to embedd images... // We need to create a "multipart/related" message. // otherwise image will appear as attached file parts.setSubType("related"); } // put all parts together msg.setContent(parts); Transport transport = null; try { transport = session.getTransport(protocol); String authPass = getPassword(authenticationPassword); if (usingAuthentication) { if (!Const.isEmpty(port)) { transport.connect(environmentSubstitute(Const.NVL(server, "")), Integer.parseInt(environmentSubstitute(Const.NVL(port, ""))), environmentSubstitute(Const.NVL(authenticationUser, "")), authPass); } else { transport.connect(environmentSubstitute(Const.NVL(server, "")), environmentSubstitute(Const.NVL(authenticationUser, "")), authPass); } } else { transport.connect(); } transport.sendMessage(msg, msg.getAllRecipients()); } finally { if (transport != null) { transport.close(); } } } catch (IOException e) { logError("Problem while sending message: " + e.toString()); result.setNrErrors(1); } catch (MessagingException mex) { logError("Problem while sending message: " + mex.toString()); result.setNrErrors(1); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { logError(" ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) { logError(" " + invalid[i]); result.setNrErrors(1); } } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { logError(" ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) { logError(" " + validUnsent[i]); result.setNrErrors(1); } } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { // System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) { logError(" " + validSent[i]); result.setNrErrors(1); } } } if (ex instanceof MessagingException) { ex = ((MessagingException) ex).getNextException(); } else { ex = null; } } while (ex != null); } finally { if (masterZipfile != null && masterZipfile.exists()) { masterZipfile.delete(); } } if (result.getNrErrors() > 0) { result.setResult(false); } else { result.setResult(true); } return result; }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Returns the signed part of the passed data or null if the data is not detected to be signed*/ public Part getSignedPart(byte[] data, String contentType) throws Exception { BCCryptoHelper helper = new BCCryptoHelper(); MimeBodyPart possibleSignedPart = new MimeBodyPart(); possibleSignedPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType))); possibleSignedPart.setHeader("content-type", contentType); return (helper.getSignedEmbeddedPart(possibleSignedPart)); }
From source file:org.pentaho.di.trans.steps.mail.Mail.java
private void addAttachedContent(String filename, String fileContent) throws Exception { // create a data source MimeBodyPart mbp = new MimeBodyPart(); // get a data Handler to manipulate this file type; mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(fileContent.getBytes(), "application/x-any"))); // include the file in the data source mbp.setFileName(filename);//ww w . j a v a 2 s . c o m // add the part with the file in the BodyPart(); data.parts.addBodyPart(mbp); }
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 . j av a 2s . c o m String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); int smptPort = 25; if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) { logger.debug("Smtp user not configured"); user = null; } // throw new Exception("Smtp user not configured"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) { logger.debug("Smtp password not configured"); } // throw new Exception("Smtp password not configured"); String mailSubj = sInfo.getMailSubj(); mailSubj = StringUtilities.substituteParametersInString(mailSubj, parMap, null, false); String mailTxt = sInfo.getMailTxt(); String[] recipients = findRecipients(sInfo, biobj, dataStore); if (recipients == null || recipients.length == 0) { logger.error("No recipients found for email sending!!!"); return; } //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", smptPort); // open session Session session = null; // create autheticator object Authenticator auth = null; if (user != null) { auth = new SMTPAuthenticator(user, pass); props.put("mail.smtp.auth", "true"); session = Session.getDefaultInstance(props, auth); logger.error("Session.getDefaultInstance(props, auth)"); } else { session = Session.getDefaultInstance(props); logger.error("Session.getDefaultInstance(props)"); } // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type String subject = mailSubj + " " + biobj.getName() + toBeAppendedToName; msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt + "\n" + toBeAppendedToDescription); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = new SchedulerDataSource(response, retCT, biobj.getName() + toBeAppendedToName + fileExt); mbp2.setDataHandler(new DataHandler(sds)); mbp2.setFileName(sds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); // send message Transport.send(msg); } catch (Exception e) { logger.error("Error while sending schedule result mail", e); } finally { logger.debug("OUT"); } }
From source file:userInterface.EnergySourceBoardSupervisor.ManageEnergyConsumptionsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; message = "Some of the appliances in your house are running inefficient." + "\n" + "Kindly check or replace your appliance " + "\n" + "Check the attachment for details or visit your account"; Properties props = System.getProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", 587); props.put("mail.smtp.user", from); Session session = Session.getDefaultInstance(props); MimeMessage mimeMessage = new MimeMessage(session); try {/*ww w .j a v a2s . c o m*/ mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Energy Board"); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(message); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(path); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(name_attach.getText() + ".png"); multipart.addBodyPart(messageBodyPart); mimeMessage.setContent(multipart); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); System.out.println("sent"); transport.close(); } catch (MessagingException me) { } }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/**Verifies the signature of the passed message. If the transfer mode is unencrypted/unsigned, a new Bodypart will be constructed *@return the payload part, this is important to compute the MIC later *///from ww w. ja v a 2s . c o m private Part verifySignature(AS2Message message, Partner sender, String contentType) throws Exception { if (this.certificateManagerSignature == null) { throw new AS2Exception(AS2Exception.PROCESSING_ERROR, "AS2MessageParser.verifySignature: pass a certification manager for the signature before calling verifySignature()", message); } AS2Info as2Info = message.getAS2Info(); if (!as2Info.isMDN()) { AS2MessageInfo messageInfo = (AS2MessageInfo) as2Info; if (messageInfo.getEncryptionType() != AS2Message.ENCRYPTION_NONE) { InputStream memIn = message.getDecryptedRawDataInputStream(); MimeBodyPart testPart = new MimeBodyPart(memIn); memIn.close(); contentType = testPart.getContentType(); } } Part signedPart = this.getSignedPart(message.getDecryptedRawData(), contentType); //part is NOT signed but is defined to be signed if (signedPart == null) { as2Info.setSignType(AS2Message.SIGNATURE_NONE); if (as2Info.isMDN()) { this.logger.log(Level.INFO, this.rb.getResourceString("mdn.notsigned", as2Info.getMessageId()), as2Info); //MDN is not signed but should be signed if (sender.isSignedMDN()) { this.logger.log(Level.SEVERE, this.rb.getResourceString("mdn.unsigned.error", new Object[] { as2Info.getMessageId(), sender.getName(), }), as2Info); } } else { this.logger.log(Level.INFO, this.rb.getResourceString("msg.notsigned", as2Info.getMessageId()), as2Info); } if (!as2Info.isMDN() && sender.getSignType() != AS2Message.SIGNATURE_NONE) { throw new AS2Exception(AS2Exception.INSUFFICIENT_SECURITY_ERROR, "Incoming messages from AS2 partner " + sender.getAS2Identification() + " are defined to be signed.", message); } //if the message has been unsigned it is required to set a new datasource MimeBodyPart unsignedPart = new MimeBodyPart(); unsignedPart.setDataHandler( new DataHandler(new ByteArrayDataSource(message.getDecryptedRawData(), contentType))); unsignedPart.setHeader("content-type", contentType); return (unsignedPart); } else { //it is definitly a signed mdn if (as2Info.isMDN()) { if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("mdn.signed", as2Info.getMessageId()), as2Info); } as2Info.setSignType(this.getDigestFromSignature(signedPart)); //MDN is signed but shouldn't be signed' if (!sender.isSignedMDN()) { if (this.logger != null) { this.logger.log(Level.WARNING, this.rb.getResourceString("mdn.signed.error", new Object[] { as2Info.getMessageId(), sender.getName(), }), as2Info); } } } else { //its no MDN, its a AS2 message if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("msg.signed", as2Info.getMessageId()), as2Info); } int signDigest = this.getDigestFromSignature(signedPart); String digest = null; if (signDigest == AS2Message.SIGNATURE_SHA1) { digest = "SHA1"; } else if (signDigest == AS2Message.SIGNATURE_MD5) { digest = "MD5"; } as2Info.setSignType(signDigest); if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("signature.analyzed.digest", new Object[] { as2Info.getMessageId(), digest }), as2Info); } } } MimeBodyPart payloadPart = null; try { String signAlias = this.certificateManagerSignature .getAliasByFingerprint(sender.getSignFingerprintSHA1()); payloadPart = this.verifySignedPartUsingAlias(message, signAlias, signedPart, contentType); } catch (AS2Exception e) { //retry to verify the signature with the second certificate if this is possible String secondAlias = this.certificateManagerSignature .getAliasByFingerprint(sender.getSignFingerprintSHA1(2)); if (secondAlias != null) { payloadPart = this.verifySignedPartUsingAlias(message, secondAlias, signedPart, contentType); } else { throw e; } } return (payloadPart); }
From source file:nl.nn.adapterframework.http.HttpSender.java
protected void addMtomMultiPartToPostMethod(PostMethod hmethod, String message, ParameterValueList parameters, ParameterResolutionContext prc) throws SenderException, MessagingException, IOException { MyMimeMultipart mimeMultipart = new MyMimeMultipart("related"); String start = null;/* w w w . j a v a 2 s. c o m*/ if (StringUtils.isNotEmpty(getInputMessageParam())) { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(message, "application/xop+xml; charset=UTF-8; type=\"text/xml\""); start = "<" + getInputMessageParam() + ">"; mimeBodyPart.setContentID(start); ; mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (string)part [" + getInputMessageParam() + "] with value [" + message + "]"); } if (parameters != null) { for (int i = 0; i < parameters.size(); i++) { ParameterValue pv = parameters.getParameterValue(i); String paramType = pv.getDefinition().getType(); String name = pv.getDefinition().getName(); if (Parameter.TYPE_INPUTSTREAM.equals(paramType)) { Object value = pv.getValue(); if (value instanceof FileInputStream) { FileInputStream fis = (FileInputStream) value; String fileName = null; String sessionKey = pv.getDefinition().getSessionKey(); if (sessionKey != null) { fileName = (String) prc.getSession().get(sessionKey + "Name"); } MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary"); mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT); ByteArrayDataSource ds = new ByteArrayDataSource(fis, "application/octet-stream"); mimeBodyPart.setDataHandler(new DataHandler(ds)); mimeBodyPart.setFileName(fileName); mimeBodyPart.setContentID("<" + name + ">"); mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (file)part [" + name + "] with value [" + value + "] and name [" + fileName + "]"); } else { throw new SenderException(getLogPrefix() + "unknown inputstream [" + value.getClass() + "] for parameter [" + name + "]"); } } else { String value = pv.asStringValue(""); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(value, "text/xml"); if (start == null) { start = "<" + name + ">"; mimeBodyPart.setContentID(start); } else { mimeBodyPart.setContentID("<" + name + ">"); } mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug( getLogPrefix() + "appended (string)part [" + name + "] with value [" + value + "]"); } } } if (StringUtils.isNotEmpty(getMultipartXmlSessionKey())) { String multipartXml = (String) prc.getSession().get(getMultipartXmlSessionKey()); if (StringUtils.isEmpty(multipartXml)) { log.warn(getLogPrefix() + "sessionKey [" + getMultipartXmlSessionKey() + "] is empty"); } else { Element partsElement; try { partsElement = XmlUtils.buildElement(multipartXml); } catch (DomBuilderException e) { throw new SenderException(getLogPrefix() + "error building multipart xml", e); } Collection parts = XmlUtils.getChildTags(partsElement, "part"); if (parts == null || parts.size() == 0) { log.warn(getLogPrefix() + "no part(s) in multipart xml [" + multipartXml + "]"); } else { int c = 0; Iterator iter = parts.iterator(); while (iter.hasNext()) { c++; Element partElement = (Element) iter.next(); //String partType = partElement.getAttribute("type"); String partName = partElement.getAttribute("name"); String partMimeType = partElement.getAttribute("mimeType"); String partSessionKey = partElement.getAttribute("sessionKey"); Object partObject = prc.getSession().get(partSessionKey); if (partObject instanceof FileInputStream) { FileInputStream fis = (FileInputStream) partObject; MimeBodyPart mimeBodyPart = new PreencodedMimeBodyPart("binary"); mimeBodyPart.setDisposition(javax.mail.Part.ATTACHMENT); ByteArrayDataSource ds = new ByteArrayDataSource(fis, (partMimeType == null ? "application/octet-stream" : partMimeType)); mimeBodyPart.setDataHandler(new DataHandler(ds)); mimeBodyPart.setFileName(partName); mimeBodyPart.setContentID("<" + partName + ">"); mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (file)part [" + partSessionKey + "] with value [" + partObject + "] and name [" + partName + "]"); } else { String partValue = (String) prc.getSession().get(partSessionKey); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(partValue, "text/xml"); if (start == null) { start = "<" + partName + ">"; mimeBodyPart.setContentID(start); } else { mimeBodyPart.setContentID("<" + partName + ">"); } mimeMultipart.addBodyPart(mimeBodyPart); if (log.isDebugEnabled()) log.debug(getLogPrefix() + "appended (string)part [" + partSessionKey + "] with value [" + partValue + "]"); } } } } } MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties())); mimeMessage.setContent(mimeMultipart); mimeMessage.saveChanges(); InputStreamRequestEntity request = new InputStreamRequestEntity(mimeMessage.getInputStream()); hmethod.setRequestEntity(request); String contentTypeMtom = "multipart/related; type=\"application/xop+xml\"; start=\"" + start + "\"; start-info=\"text/xml\"; boundary=\"" + mimeMultipart.getBoundary() + "\""; Header header = new Header("Content-Type", contentTypeMtom); hmethod.addRequestHeader(header); }
From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.Shipper.java
/** * Sends an email to the given id including a link to the password page. The * link contains the refID./* ww w . ja va 2s . c om*/ * * @param emailType * - refers to the email that shall be sent, 0 sends an email for * newly registered users, 1 sends a standard password-reset * email * @param emailaddress * @param refID * @return */ public boolean sendPasswordLinkToEmail(int emailType, User user, String refID) { String salutation = ""; if (user.getGender().equalsIgnoreCase("male")) { salutation = "geehrter Herr " + user.getName(); } else { salutation = "geehrte Frau " + user.getName(); } MailAuthenticator auth = new MailAuthenticator(emailProperties.getProperty("mail.user"), emailProperties.getProperty("mail.user.password")); // Login Properties props = (Properties) emailProperties.clone(); props.remove("mail.user"); props.remove("mail.user.password"); Session session = Session.getInstance(props, auth); String htmlContent = emailBody; htmlContent = htmlContent.replaceFirst("TITLE", emailProperties.getProperty("mail.skeleton.type." + emailType + ".title")); htmlContent = htmlContent.replaceFirst("MESSAGESUBJECT", emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject")); htmlContent = htmlContent.replaceFirst("HEADER1", emailProperties.getProperty("mail.skeleton.type." + emailType + ".header1")); htmlContent = htmlContent.replaceFirst("MESSAGE", emailProperties.getProperty("mail.skeleton.type." + emailType + ".message")); htmlContent = htmlContent.replaceFirst("SALUTATION", salutation); htmlContent = htmlContent.replaceFirst("TOPLEVELDOMAIN", emailProperties.getProperty("mail.service.domain")); htmlContent = htmlContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name")); htmlContent = htmlContent.replaceFirst("REFERER", refID); htmlContent = htmlContent.replaceFirst("BCKRGIMAGE", "'cid:header-image'"); htmlContent = htmlContent.replaceFirst("DASH", "'cid:dash'"); String textContent = emailProperties.getProperty("mail.skeleton.type." + emailType + ".title") + " - " + emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject") + "\n \n" + emailProperties.getProperty("mail.skeleton.type." + emailType + ".message"); textContent = textContent.replaceFirst("TOPLEVELDOMAIN", emailProperties.getProperty("mail.service.domain")); textContent = textContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name")); textContent = textContent.replaceFirst("REFERER", refID); textContent = textContent.replaceFirst("SALUTATION", salutation); textContent = textContent.replaceAll("<br>", "\n"); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(emailProperties.getProperty("mail.user"))); msg.setRecipients(javax.mail.Message.RecipientType.TO, user.getEmailaddress()); msg.setSentDate(new Date()); msg.setSubject(emailProperties.getProperty("mail.skeleton.type." + emailType + ".subject")); Multipart mp = new MimeMultipart("alternative"); // plaintext MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(textContent); mp.addBodyPart(textPart); // html MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent, "text/html; charset=UTF-8"); mp.addBodyPart(htmlPart); MimeBodyPart imagePart = new MimeBodyPart(); DataSource fds = null; try { fds = new FileDataSource( new File(new URL((String) emailProperties.get("mail.image.headerbackground")).getFile())); } catch (MalformedURLException e) { Logger.getLogger(this.getClass()).error(e); } imagePart.setDataHandler(new DataHandler(fds)); imagePart.setHeader("Content-ID", "header-image"); mp.addBodyPart(imagePart); MimeBodyPart imagePart2 = new MimeBodyPart(); DataSource fds2 = null; try { fds2 = new FileDataSource( new File(new URL((String) emailProperties.get("mail.image.dash")).getFile())); } catch (MalformedURLException e) { Logger.getLogger(this.getClass()).error(e); } imagePart2.setDataHandler(new DataHandler(fds2)); imagePart2.setHeader("Content-ID", "dash"); mp.addBodyPart(imagePart2); msg.setContent(mp); Transport.send(msg); } catch (Exception e) { Logger.getLogger(this.getClass()).error(e); return false; } return true; }