List of usage examples for javax.mail.internet MimeMultipart setSubType
public synchronized void setSubType(String subtype) throws MessagingException
From source file:at.molindo.notify.channel.mail.AbstractMailClient.java
@Override public synchronized void send(Dispatch dispatch) throws MailException { Message message = dispatch.getMessage(); String recipient = dispatch.getParams().get(MailChannel.RECIPIENT); String recipientName = dispatch.getParams().get(MailChannel.RECIPIENT_NAME); String subject = message.getSubject(); try {/* ww w. j a v a 2s . c o m*/ MimeMessage mm = new MimeMessage(getSmtpSession(recipient)) { @Override protected void updateMessageID() throws MessagingException { String domain = _from.getAddress(); int idx = _from.getAddress().indexOf('@'); if (idx >= 0) { domain = domain.substring(idx + 1); } setHeader("Message-ID", "<" + UUID.randomUUID() + "@" + domain + ">"); } }; mm.setFrom(_from); mm.setSender(_from); InternetAddress replyTo = getReplyTo(); if (replyTo != null) { mm.setReplyTo(new Address[] { replyTo }); } mm.setHeader("X-Mailer", "molindo-notify"); mm.setSentDate(new Date()); mm.setRecipient(RecipientType.TO, new InternetAddress(recipient, recipientName, CharsetUtils.UTF_8.displayName())); mm.setSubject(subject, CharsetUtils.UTF_8.displayName()); if (_format == Format.HTML) { if (message.getType() == Type.TEXT) { throw new MailException("can't send HTML mail from TEXT message", false); } mm.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html"); } else if (_format == Format.TEXT || _format == Format.MULTI && message.getType() == Type.TEXT) { mm.setText(message.getText(), CharsetUtils.UTF_8.displayName()); } else if (_format == Format.MULTI) { MimeBodyPart html = new MimeBodyPart(); html.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html"); MimeBodyPart text = new MimeBodyPart(); text.setText(message.getText(), CharsetUtils.UTF_8.displayName()); /* * The formats are ordered by how faithful they are to the * original, with the least faithful first and the most faithful * last. (http://en.wikipedia.org/wiki/MIME#Alternative) */ MimeMultipart mmp = new MimeMultipart(); mmp.setSubType("alternative"); mmp.addBodyPart(text); mmp.addBodyPart(html); mm.setContent(mmp); } else { throw new NotifyRuntimeException( "unexpected format (" + _format + ") or type (" + message.getType() + ")"); } send(mm); } catch (final MessagingException e) { throw new MailException( "could not send mail from " + _from + " to " + recipient + " (" + toErrorMessage(e) + ")", e, isTemporary(e)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("utf8 unknown?", e); } }
From source file:lucee.runtime.net.mail.HtmlEmailImpl.java
/** * @throws EmailException EmailException * @throws MessagingException MessagingException *///from w w w. j av a 2s.c om private void buildNoAttachments() throws MessagingException, EmailException { MimeMultipart container = this.getContainer(); MimeMultipart subContainerHTML = new MimeMultipart("related"); container.setSubType("alternative"); BodyPart msgText = null; BodyPart msgHtml = null; if (!StringUtil.isEmpty(this.text)) { msgText = this.getPrimaryBodyPart(); if (!StringUtil.isEmpty(this.charset)) { msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset); } else { msgText.setContent(this.text, Email.TEXT_PLAIN); } } if (!StringUtil.isEmpty(this.html)) { // if the txt part of the message was null, then the html part // will become the primary body part if (msgText == null) { msgHtml = getPrimaryBodyPart(); } else { if (this.inlineImages.size() > 0) { msgHtml = new MimeBodyPart(); subContainerHTML.addBodyPart(msgHtml); } else { msgHtml = new MimeBodyPart(); container.addBodyPart(msgHtml, 1); } } if (!StringUtil.isEmpty(this.charset)) { msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset); } else { msgHtml.setContent(this.html, Email.TEXT_HTML); } Iterator iter = this.inlineImages.iterator(); while (iter.hasNext()) { subContainerHTML.addBodyPart((BodyPart) iter.next()); } if (this.inlineImages.size() > 0) { // add sub container to message this.addPart(subContainerHTML); } } }
From source file:lucee.runtime.net.mail.HtmlEmailImpl.java
/** * @throws EmailException EmailException * @throws MessagingException MessagingException *//*from w ww .j ava 2 s . co m*/ private void buildAttachments() throws MessagingException, EmailException { MimeMultipart container = this.getContainer(); MimeMultipart subContainer = null; MimeMultipart subContainerHTML = new MimeMultipart("related"); BodyPart msgHtml = null; BodyPart msgText = null; container.setSubType("mixed"); subContainer = new MimeMultipart("alternative"); if (!StringUtil.isEmpty(this.text)) { msgText = new MimeBodyPart(); subContainer.addBodyPart(msgText); if (!StringUtil.isEmpty(this.charset)) { msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset); } else { msgText.setContent(this.text, Email.TEXT_PLAIN); } } if (!StringUtil.isEmpty(this.html)) { if (this.inlineImages.size() > 0) { msgHtml = new MimeBodyPart(); subContainerHTML.addBodyPart(msgHtml); } else { msgHtml = new MimeBodyPart(); subContainer.addBodyPart(msgHtml); } if (!StringUtil.isEmpty(this.charset)) { msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset); } else { msgHtml.setContent(this.html, Email.TEXT_HTML); } Iterator iter = this.inlineImages.iterator(); while (iter.hasNext()) { subContainerHTML.addBodyPart((BodyPart) iter.next()); } } // add sub containers to message this.addPart(subContainer, 0); if (this.inlineImages.size() > 0) { // add sub container to message this.addPart(subContainerHTML, 1); } }
From source file:immf.MyHtmlEmail.java
/** * @throws EmailException EmailException * @throws MessagingException MessagingException *//*w ww. j a v a 2 s.c o m*/ private void build() throws MessagingException, EmailException { MimeMultipart rootContainer = this.getContainer(); MimeMultipart bodyEmbedsContainer = rootContainer; MimeMultipart bodyContainer = rootContainer; BodyPart msgHtml = null; BodyPart msgText = null; rootContainer.setSubType("mixed"); // determine how to form multiparts of email if (StringUtils.isNotEmpty(this.html) && this.inlineEmbeds.size() > 0) { //If HTML body and embeds are used, create a related container and add it to the root container bodyEmbedsContainer = new MimeMultipart("related"); bodyContainer = bodyEmbedsContainer; this.addPart(bodyEmbedsContainer, 0); //If TEXT body was specified, create a alternative container and add it to the embeds container if (StringUtils.isNotEmpty(this.text)) { bodyContainer = new MimeMultipart("alternative"); BodyPart bodyPart = createBodyPart(); try { bodyPart.setContent(bodyContainer); bodyEmbedsContainer.addBodyPart(bodyPart, 0); } catch (MessagingException me) { throw new EmailException(me); } } } else if (StringUtils.isNotEmpty(this.text) && StringUtils.isNotEmpty(this.html)) { //If both HTML and TEXT bodies are provided, create a alternative container and add it to the root container bodyContainer = new MimeMultipart("alternative"); this.addPart(bodyContainer, 0); } if (StringUtils.isNotEmpty(this.html)) { msgHtml = new MimeBodyPart(); bodyContainer.addBodyPart(msgHtml, 0); // apply default charset if one has been set if (StringUtils.isNotEmpty(this.charset)) { msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset); } else { msgHtml.setContent(this.html, Email.TEXT_HTML); } if (contentTransferEncoding != null) { msgHtml.setHeader("Content-Transfer-Encoding", contentTransferEncoding); } Iterator<InlineImage> iter = this.inlineEmbeds.values().iterator(); while (iter.hasNext()) { InlineImage ii = (InlineImage) iter.next(); bodyEmbedsContainer.addBodyPart(ii.getMbp()); } } if (StringUtils.isNotEmpty(this.text)) { msgText = new MimeBodyPart(); bodyContainer.addBodyPart(msgText, 0); // apply default charset if one has been set if (StringUtils.isNotEmpty(this.charset)) { msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset); } else { msgText.setContent(this.text, Email.TEXT_PLAIN); } if (contentTransferEncoding != null) { msgText.setHeader("Content-Transfer-Encoding", contentTransferEncoding); } } }
From source file:de.betterform.connector.serializer.MultipartRelatedSerializer.java
public void serialize(Submission submission, Node node, SerializerRequestWrapper wrapper, String defaultEncoding) throws Exception { Map cache = new HashMap(); MimeMultipart multipart = new MimeMultipart(); MimeBodyPart part = new MimeBodyPart(); multipart.addBodyPart(part);//from w w w .j av a 2 s .c o m String encoding = defaultEncoding; if (submission.getEncoding() != null) { encoding = submission.getEncoding(); } if (node.getNodeType() == Node.ELEMENT_NODE || node.getNodeType() == Node.DOCUMENT_NODE) { part.setText(new String(serializeXML(multipart, cache, submission, node, encoding), encoding), encoding); } else { part.setText(node.getTextContent()); } part.setContentID("<instance.xml@start>"); part.addHeader("Content-Type", "application/xml"); part.addHeader("Content-Transfer-Encoding", "base64"); part.setDisposition("attachment"); part.setFileName("instance.xml"); multipart.setSubType("related; type=\"" + submission.getMediatype() + "\"; start=\"instance.xml@start\""); // FIXME: Is this a global http header or a local mime header? wrapper.getBodyStream() .write(("Content-Type: " + multipart.getContentType() + "\n\nThis is a MIME message.\n") .getBytes(encoding)); multipart.writeTo(wrapper.getBodyStream()); }
From source file:com.sonicle.webtop.mail.Service.java
public Message createMessage(String from, SimpleMessage smsg, List<JsAttachment> attachments, boolean tosave) throws Exception { MimeMessage msg = null;//from w ww .j a va 2s . c o m boolean success = true; String[] to = SimpleMessage.breakAddr(smsg.getTo()); String[] cc = SimpleMessage.breakAddr(smsg.getCc()); String[] bcc = SimpleMessage.breakAddr(smsg.getBcc()); String replyTo = smsg.getReplyTo(); msg = new MimeMessage(mainAccount.getMailSession()); msg.setFrom(getInternetAddress(from)); InternetAddress ia = null; //set the TO recipient for (int q = 0; q < to.length; q++) { // Service.logger.debug("to["+q+"]="+to[q]); to[q] = to[q].replace(',', ' '); try { ia = getInternetAddress(to[q]); } catch (AddressException exc) { throw new AddressException(to[q]); } msg.addRecipient(Message.RecipientType.TO, ia); } //set the CC recipient for (int q = 0; q < cc.length; q++) { cc[q] = cc[q].replace(',', ' '); try { ia = getInternetAddress(cc[q]); } catch (AddressException exc) { throw new AddressException(cc[q]); } msg.addRecipient(Message.RecipientType.CC, ia); } //set BCC recipients for (int q = 0; q < bcc.length; q++) { bcc[q] = bcc[q].replace(',', ' '); try { ia = getInternetAddress(bcc[q]); } catch (AddressException exc) { throw new AddressException(bcc[q]); } msg.addRecipient(Message.RecipientType.BCC, ia); } //set reply to addr if (replyTo != null && replyTo.length() > 0) { Address[] replyaddr = new Address[1]; replyaddr[0] = getInternetAddress(replyTo); msg.setReplyTo(replyaddr); } //add any header String headerLines[] = smsg.getHeaderLines(); for (int i = 0; i < headerLines.length; ++i) { if (!headerLines[i].startsWith("Sonicle-reply-folder")) { msg.addHeaderLine(headerLines[i]); } } //add reply/references String inreplyto = smsg.getInReplyTo(); String references[] = smsg.getReferences(); String replyfolder = smsg.getReplyFolder(); if (inreplyto != null) { msg.setHeader("In-Reply-To", inreplyto); } if (references != null && references[0] != null) { msg.setHeader("References", references[0]); } if (tosave) { if (replyfolder != null) { msg.setHeader("Sonicle-reply-folder", replyfolder); } msg.setHeader("Sonicle-draft", "true"); } //add forward data String forwardedfrom = smsg.getForwardedFrom(); String forwardedfolder = smsg.getForwardedFolder(); if (forwardedfrom != null) { msg.setHeader("Forwarded-From", forwardedfrom); } if (tosave) { if (forwardedfolder != null) { msg.setHeader("Sonicle-forwarded-folder", forwardedfolder); } msg.setHeader("Sonicle-draft", "true"); } //set the subject String subject = smsg.getSubject(); try { //subject=MimeUtility.encodeText(smsg.getSubject(), "ISO-8859-1", null); subject = MimeUtility.encodeText(smsg.getSubject()); } catch (Exception exc) { } msg.setSubject(subject); //set priority int priority = smsg.getPriority(); if (priority != 3) { msg.setHeader("X-Priority", "" + priority); //set receipt } String receiptTo = from; try { receiptTo = MimeUtility.encodeText(from, "ISO-8859-1", null); } catch (Exception exc) { } if (smsg.getReceipt()) { msg.setHeader("Disposition-Notification-To", from); //see if there are any new attachments for the message } int noAttach; int newAttach; if (attachments == null) { newAttach = 0; } else { newAttach = attachments.size(); } //get the array of the old attachments Part[] oldParts = smsg.getAttachments(); //check if there are old attachments if (oldParts == null) { noAttach = 0; } else { //old attachments exist noAttach = oldParts.length; } if ((newAttach > 0) || (noAttach > 0) || !smsg.getMime().equalsIgnoreCase("text/plain")) { // create the main Multipart MimeMultipart mp = new MimeMultipart("mixed"); MimeMultipart unrelated = null; String textcontent = smsg.getTextContent(); //if is text, or no alternative text is available, add the content as one single body part //else create a multipart/alternative with both rich and text mime content if (textcontent == null || smsg.getMime().equalsIgnoreCase("text/plain")) { MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); mp.addBodyPart(mbp1); } else { MimeMultipart alternative = new MimeMultipart("alternative"); //the rich part MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.setContent(smsg.getContent(), MailUtils.buildPartContentType(smsg.getMime(), "UTF-8")); //the text part MimeBodyPart mbp1 = new MimeBodyPart(); /* ByteArrayOutputStream bos=new ByteArrayOutputStream(textcontent.length()); com.sun.mail.util.QPEncoderStream qpe=new com.sun.mail.util.QPEncoderStream(bos); for(int i=0;i<textcontent.length();++i) { try { qpe.write(textcontent.charAt(i)); } catch(IOException exc) { Service.logger.error("Exception",exc); } } textcontent=new String(bos.toByteArray());*/ mbp1.setContent(textcontent, MailUtils.buildPartContentType("text/plain", "UTF-8")); // mbp1.setHeader("Content-transfer-encoding","quoted-printable"); alternative.addBodyPart(mbp1); alternative.addBodyPart(mbp2); MimeBodyPart altbody = new MimeBodyPart(); altbody.setContent(alternative); mp.addBodyPart(altbody); } if (noAttach > 0) { //if there are old attachments // create the parts with the attachments //MimeBodyPart[] mbps2 = new MimeBodyPart[noAttach]; //Part[] mbps2 = new Part[noAttach]; //for(int e = 0;e < noAttach;e++) { // mbps2[e] = (Part)oldParts[e]; //}//end for e //add the old attachment parts for (int r = 0; r < noAttach; r++) { Object content = null; String contentType = null; String contentFileName = null; if (oldParts[r] instanceof Message) { // Service.logger.debug("Attachment is a message"); Message msgpart = (Message) oldParts[r]; MimeMessage mm = new MimeMessage(mainAccount.getMailSession()); mm.addFrom(msgpart.getFrom()); mm.setRecipients(Message.RecipientType.TO, msgpart.getRecipients(Message.RecipientType.TO)); mm.setRecipients(Message.RecipientType.CC, msgpart.getRecipients(Message.RecipientType.CC)); mm.setRecipients(Message.RecipientType.BCC, msgpart.getRecipients(Message.RecipientType.BCC)); mm.setReplyTo(msgpart.getReplyTo()); mm.setSentDate(msgpart.getSentDate()); mm.setSubject(msgpart.getSubject()); mm.setContent(msgpart.getContent(), msgpart.getContentType()); content = mm; contentType = "message/rfc822"; } else { // Service.logger.debug("Attachment is not a message"); content = oldParts[r].getContent(); if (!(content instanceof MimeMultipart)) { contentType = oldParts[r].getContentType(); contentFileName = oldParts[r].getFileName(); } } MimeBodyPart mbp = new MimeBodyPart(); if (contentFileName != null) { mbp.setFileName(contentFileName); // Service.logger.debug("adding attachment mime "+contentType+" filename "+contentFileName); contentType += "; name=\"" + contentFileName + "\""; } if (content instanceof MimeMultipart) mbp.setContent((MimeMultipart) content); else mbp.setDataHandler(new DataHandler(content, contentType)); mp.addBodyPart(mbp); } } //end if, adding old attachments if (newAttach > 0) { //if there are new attachments // create the parts with the attachments MimeBodyPart[] mbps = new MimeBodyPart[newAttach]; for (int e = 0; e < newAttach; e++) { mbps[e] = new MimeBodyPart(); // attach the file to the message JsAttachment attach = (JsAttachment) attachments.get(e); UploadedFile upfile = getUploadedFile(attach.uploadId); FileDataSource fds = new FileDataSource(upfile.getFile()); mbps[e].setDataHandler(new DataHandler(fds)); // filename starts has format: // "_" + userid + sessionId + "_" + filename // if (attach.inline) { mbps[e].setDisposition(Part.INLINE); } String contentFileName = attach.fileName.trim(); mbps[e].setFileName(contentFileName); String contentType = upfile.getMediaType() + "; name=\"" + contentFileName + "\""; mbps[e].setHeader("Content-type", contentType); if (attach.cid != null && attach.cid.trim().length() > 0) { mbps[e].setHeader("Content-ID", "<" + attach.cid + ">"); mbps[e].setHeader("X-Attachment-Id", attach.cid); mbps[e].setDisposition(Part.INLINE); if (unrelated == null) unrelated = new MimeMultipart("mixed"); } } //end for e //add the new attachment parts if (unrelated == null) { for (int r = 0; r < newAttach; r++) mp.addBodyPart(mbps[r]); } else { //mp becomes the related part with text parts and cids MimeMultipart related = mp; related.setSubType("related"); //nest the related part into the mixed part mp = unrelated; MimeBodyPart mbd = new MimeBodyPart(); mbd.setContent(related); mp.addBodyPart(mbd); for (int r = 0; r < newAttach; r++) { if (mbps[r].getHeader("Content-ID") != null) { related.addBodyPart(mbps[r]); } else { mp.addBodyPart(mbps[r]); } } } } //end if, adding new attachments // // msg.addHeaderLine("This is a multi-part message in MIME format."); // add the Multipart to the message msg.setContent(mp); } else { //end if newattach msg.setText(smsg.getContent()); } //singlepart message msg.setSentDate(new java.util.Date()); return msg; }
From source file:org.apache.camel.component.mail.MailBinding.java
private MimeMultipart createMixedMultipartAttachments(MailConfiguration configuration, Exchange exchange) throws MessagingException, IOException { // fill the body with text MimeMultipart multipart = new MimeMultipart(); multipart.setSubType("mixed"); addBodyToMultipart(configuration, multipart, exchange); String partDisposition = configuration.isUseInlineAttachments() ? Part.INLINE : Part.ATTACHMENT; if (exchange.getIn().hasAttachments()) { addAttachmentsToMultipart(multipart, partDisposition, exchange); }// w w w. j av a 2s . co m return multipart; }
From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java
/** * Fill the body of a message already created. * The result message depends on the information given. * //w ww . j a v a2s . c om * @param message * @param text * @param html * @param parts * @return The composed message * @throws MessagingException * @throws IOException */ @SuppressWarnings("rawtypes") public static Message composeMessage(Message message, String text, String html, List parts) throws MessagingException, IOException { MimeBodyPart txtPart = null; MimeBodyPart htmlPart = null; MimeMultipart mimeMultipart = null; if (text == null && html == null) { text = ""; } if (text != null) { txtPart = new MimeBodyPart(); txtPart.setContent(text, "text/plain"); } if (html != null) { htmlPart = new MimeBodyPart(); htmlPart.setContent(html, "text/html"); } if (html != null && text != null) { mimeMultipart = new MimeMultipart(); mimeMultipart.setSubType("alternative"); mimeMultipart.addBodyPart(txtPart); mimeMultipart.addBodyPart(htmlPart); } if (parts == null || parts.isEmpty()) { if (mimeMultipart != null) { message.setContent(mimeMultipart); } else if (html != null) { message.setText(html); message.setHeader("Content-type", "text/html"); } else if (text != null) { message.setText(text); } } else { MimeBodyPart bodyPart = new MimeBodyPart(); if (mimeMultipart != null) { bodyPart.setContent(mimeMultipart); } else if (html != null) { bodyPart.setText(html); bodyPart.setHeader("Content-type", "text/html"); } else if (text != null) { bodyPart.setText(text); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); for (Object attachment : parts) { if (attachment instanceof FileItem) { multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment)); } else { multipart.addBodyPart((BodyPart) attachment); } } message.setContent(multipart); } message.saveChanges(); return message; }
From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java
/** * Fill the body of a message already created. * The result message depends on the information given. * * @param message/*from w w w .jav a 2 s .c om*/ * @param text * @param html * @param parts * @return The composed message * @throws MessagingException * @throws IOException */ @SuppressWarnings("rawtypes") public static Message composeMessage(Message message, String text, String html, List parts) throws MessagingException, IOException { MimeBodyPart txtPart = null; MimeBodyPart htmlPart = null; MimeMultipart mimeMultipart = null; if (text == null && html == null) { text = ""; } if (text != null) { txtPart = new MimeBodyPart(); txtPart.setContent(text, "text/plain; charset=UTF-8"); } if (html != null) { htmlPart = new MimeBodyPart(); htmlPart.setContent(html, "text/html; charset=UTF-8"); } if (html != null && text != null) { mimeMultipart = new MimeMultipart(); mimeMultipart.setSubType("alternative"); mimeMultipart.addBodyPart(txtPart); mimeMultipart.addBodyPart(htmlPart); } if (parts == null || parts.isEmpty()) { if (mimeMultipart != null) { message.setContent(mimeMultipart); } else if (html != null) { message.setText(html); message.setHeader("Content-type", "text/html"); } else if (text != null) { message.setText(text); } } else { MimeBodyPart bodyPart = new MimeBodyPart(); if (mimeMultipart != null) { bodyPart.setContent(mimeMultipart); } else if (html != null) { bodyPart.setText(html); bodyPart.setHeader("Content-type", "text/html"); } else if (text != null) { bodyPart.setText(text); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); for (Object attachment : parts) { if (attachment instanceof FileItem) { multipart.addBodyPart(MessageUtils.fileitemToBodypart((FileItem) attachment)); } else { multipart.addBodyPart((BodyPart) attachment); } } message.setContent(multipart); } message.saveChanges(); return message; }
From source file:org.pentaho.di.job.entries.mail.JobEntryMail.java
public Result execute(Result result, int nr) { File masterZipfile = null;/* w w w . jav a 2 s.c om*/ // 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; }