List of usage examples for javax.mail.internet MimeBodyPart setContent
@Override public void setContent(Object o, String type) throws MessagingException
From source file:voldemort.coordinator.HttpGetAllRequestExecutor.java
public void writeResponseOld(Map<ByteArray, Versioned<byte[]>> responseVersioned) { // Multipart response MimeMultipart mp = new MimeMultipart(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {/* ww w .j av a 2s .c o m*/ for (Entry<ByteArray, Versioned<byte[]>> entry : responseVersioned.entrySet()) { Versioned<byte[]> value = entry.getValue(); ByteArray keyByteArray = entry.getKey(); String base64Key = new String(Base64.encodeBase64(keyByteArray.get())); String contentLocationKey = "/" + this.storeName + "/" + base64Key; byte[] responseValue = value.getValue(); VectorClock vc = (VectorClock) value.getVersion(); VectorClockWrapper vcWrapper = new VectorClockWrapper(vc); ObjectMapper mapper = new ObjectMapper(); String eTag = ""; try { eTag = mapper.writeValueAsString(vcWrapper); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (logger.isDebugEnabled()) { logger.debug("ETAG : " + eTag); } // Create the individual body part MimeBodyPart body = new MimeBodyPart(); body.addHeader(CONTENT_TYPE, "application/octet-stream"); body.addHeader(CONTENT_LOCATION, contentLocationKey); body.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); body.addHeader(CONTENT_LENGTH, "" + responseValue.length); body.addHeader(ETAG, eTag); body.setContent(responseValue, "application/octet-stream"); mp.addBodyPart(body); } // At this point we have a complete multi-part response mp.writeTo(outputStream); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(outputStream.toByteArray()); // 1. Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // 2. Set the right headers response.setHeader(CONTENT_TYPE, "multipart/binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); // 3. Copy the data into the payload response.setContent(responseContent); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Update the stats if (this.coordinatorPerfStats != null) { long durationInNs = System.nanoTime() - startTimestampInNs; this.coordinatorPerfStats.recordTime(Tracked.GET_ALL, durationInNs); } // Write the response to the Netty Channel this.getRequestMessageEvent.getChannel().write(response); }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail from a Mail object// ww w. ja va 2s. co m */ public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({})", mail); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (mail.getFrom() != null) { InternetAddress from = new InternetAddress(mail.getFrom()); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[mail.getTo().length]; int i = 0; for (String strTo : mail.getTo()) { to[i++] = new InternetAddress(strTo); } // Build a multiparted mail with HTML and text content for better SPAM behaviour MimeMultipart content = new MimeMultipart(); if (Mail.MIME_TEXT.equals(mail.getMimeType())) { // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } else if (Mail.MIME_HTML.equals(mail.getMimeType())) { // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(mail.getContent()); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html"); htmlPart.setHeader("Content-Type", "text/html"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); } else { log.warn("Email does not specify content MIME type"); // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } for (Document doc : mail.getAttachments()) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(doc.getPath()); try { is = OKMDocument.getInstance().getContent(token, doc.getPath(), false); File tmp = File.createTempFile("okm", ".tmp"); fos = new FileOutputStream(tmp); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmp.getPath()); docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(docName); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(mail.getSubject(), "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:voldemort.coordinator.HttpGetAllRequestExecutor.java
public void writeResponse(Map<ByteArray, List<Versioned<byte[]>>> versionedResponses) throws Exception { // multiPartKeys is the outer multipart MimeMultipart multiPartKeys = new MimeMultipart(); ByteArrayOutputStream keysOutputStream = new ByteArrayOutputStream(); for (Entry<ByteArray, List<Versioned<byte[]>>> entry : versionedResponses.entrySet()) { ByteArray key = entry.getKey();// w w w. j av a 2 s . co m String contentLocationKey = "/" + this.storeName + "/" + new String(Base64.encodeBase64(key.get())); // Create the individual body part - for each key requested MimeBodyPart keyBody = new MimeBodyPart(); try { // Add the right headers keyBody.addHeader(CONTENT_TYPE, "multipart/binary"); keyBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); keyBody.addHeader(CONTENT_LOCATION, contentLocationKey); } catch (MessagingException me) { logger.error("Exception while constructing key body headers", me); keysOutputStream.close(); throw me; } // multiPartValues is the inner multipart MimeMultipart multiPartValues = new MimeMultipart(); for (Versioned<byte[]> versionedValue : entry.getValue()) { byte[] responseValue = versionedValue.getValue(); VectorClock vectorClock = (VectorClock) versionedValue.getVersion(); String serializedVC = CoordinatorUtils.getSerializedVectorClock(vectorClock); // Create the individual body part - for each versioned value of // a key MimeBodyPart valueBody = new MimeBodyPart(); try { // Add the right headers valueBody.addHeader(CONTENT_TYPE, "application/octet-stream"); valueBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); valueBody.addHeader(VoldemortHttpRequestHandler.X_VOLD_VECTOR_CLOCK, serializedVC); valueBody.setContent(responseValue, "application/octet-stream"); multiPartValues.addBodyPart(valueBody); } catch (MessagingException me) { logger.error("Exception while constructing value body part", me); keysOutputStream.close(); throw me; } } try { // Add the inner multipart as the content of the outer body part keyBody.setContent(multiPartValues); multiPartKeys.addBodyPart(keyBody); } catch (MessagingException me) { logger.error("Exception while constructing key body part", me); keysOutputStream.close(); throw me; } } try { multiPartKeys.writeTo(keysOutputStream); } catch (Exception e) { logger.error("Exception while writing mutipart to output stream", e); throw e; } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(keysOutputStream.toByteArray()); // Create the Response object HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); // Set the right headers response.setHeader(CONTENT_TYPE, "multipart/binary"); response.setHeader(CONTENT_TRANSFER_ENCODING, "binary"); // Copy the data into the payload response.setContent(responseContent); response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes()); // Update the stats if (this.coordinatorPerfStats != null) { long durationInNs = System.nanoTime() - startTimestampInNs; this.coordinatorPerfStats.recordTime(Tracked.GET_ALL, durationInNs); } // Write the response to the Netty Channel this.getRequestMessageEvent.getChannel().write(response); keysOutputStream.close(); }
From source file:com.gamesalutes.utils.email.DefaultEmailServiceImpl.java
public void send(EmailModel model) throws EmailException { if (LOGGER.isDebugEnabled()) LOGGER.debug("Sending email: " + model); if (model == null) throw new NullPointerException("model"); Properties emailProps;//from ww w . j a v a2s. c o m Session emailSession; // set the relay host as a property of the email session emailProps = new Properties(); emailProps.setProperty("mail.transport.protocol", "smtp"); emailProps.put("mail.smtp.host", host); emailProps.setProperty("mail.smtp.port", String.valueOf(port)); // set the timeouts emailProps.setProperty("mail.smtp.connectiontimeout", String.valueOf(SOCKET_CONNECT_TIMEOUT_MS)); emailProps.setProperty("mail.smtp.timeout", String.valueOf(SOCKET_IO_TIMEOUT_MS)); if (LOGGER.isDebugEnabled()) LOGGER.debug("Email properties: " + emailProps); // set up email session emailSession = Session.getInstance(emailProps, null); emailSession.setDebug(false); String from; String displayFrom; String body; String subject; List<EmailAttachment> attachments; if (model.getFrom() == null) throw new NullPointerException("from"); if (MiscUtils.isEmpty(model.getTo()) && MiscUtils.isEmpty(model.getBcc()) && MiscUtils.isEmpty(model.getCc())) throw new IllegalArgumentException("model has no addresses"); from = model.getFrom(); displayFrom = model.getDisplayFrom(); body = model.getBody(); subject = model.getSubject(); attachments = model.getAttachments(); MimeMessage emailMessage; InternetAddress emailAddressFrom; // create an email message from the current session emailMessage = new MimeMessage(emailSession); // set the from try { emailAddressFrom = new InternetAddress(from, displayFrom); emailMessage.setFrom(emailAddressFrom); } catch (Exception e) { throw new IllegalStateException(e); } if (!MiscUtils.isEmpty(model.getTo())) setEmailRecipients(emailMessage, model.getTo(), RecipientType.TO); if (!MiscUtils.isEmpty(model.getCc())) setEmailRecipients(emailMessage, model.getCc(), RecipientType.CC); if (!MiscUtils.isEmpty(model.getBcc())) setEmailRecipients(emailMessage, model.getBcc(), RecipientType.BCC); try { if (!MiscUtils.isEmpty(subject)) emailMessage.setSubject(subject); Multipart multipart = new MimeMultipart(); if (body != null) { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); //fill message String bodyContentType; // body = Utils.base64Encode(body); bodyContentType = "text/html; charset=UTF-8"; messageBodyPart.setContent(body, bodyContentType); //Content-Transfer-Encoding : base64 // messageBodyPart.addHeader("Content-Transfer-Encoding", "base64"); multipart.addBodyPart(messageBodyPart); } // Part two is attachment if (attachments != null && !attachments.isEmpty()) { try { for (EmailAttachment a : attachments) { MimeBodyPart attachBodyPart = new MimeBodyPart(); // don't base 64 encode DataSource source = new StreamDataSource( new DefaultStreamFactory(a.getInputStream(), false), a.getName(), a.getContentType()); attachBodyPart.setDataHandler(new DataHandler(source)); attachBodyPart.setFileName(a.getName()); attachBodyPart.setHeader("Content-Type", a.getContentType()); attachBodyPart.addHeader("Content-Transfer-Encoding", "base64"); // add the attachment to the message multipart.addBodyPart(attachBodyPart); } } // close all the input streams finally { for (EmailAttachment a : attachments) MiscUtils.closeStream(a.getInputStream()); } } // set the content emailMessage.setContent(multipart); emailMessage.saveChanges(); if (LOGGER.isDebugEnabled()) LOGGER.debug("Sending email message: " + emailMessage); Transport.send(emailMessage); if (LOGGER.isDebugEnabled()) LOGGER.debug("Sending email complete."); } catch (Exception e) { throw new EmailException(e); } }
From source file:org.apache.axis2.transport.mail.MailTransportSender.java
/** * Populate email with a SOAP formatted message * @param outInfo the out transport information holder * @param msgContext the message context that holds the message to be written * @throws AxisFault on error/*from w w w .j a v a 2 s . c o m*/ * @return id of the send mail message */ private String sendMail(MailOutTransportInfo outInfo, MessageContext msgContext) throws AxisFault, MessagingException, IOException { OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); // Make sure that non textual attachements are sent with base64 transfer encoding // instead of binary. format.setProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS, true); MessageFormatter messageFormatter = BaseUtils.getMessageFormatter(msgContext); if (log.isDebugEnabled()) { log.debug( "Creating MIME message using message formatter " + messageFormatter.getClass().getSimpleName()); } WSMimeMessage message = null; if (outInfo.getFromAddress() != null) { message = new WSMimeMessage(session, outInfo.getFromAddress().getAddress()); } else { message = new WSMimeMessage(session, ""); } Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); if (log.isDebugEnabled() && trpHeaders != null) { log.debug("Using transport headers: " + trpHeaders); } // set From address - first check if this is a reply, then use from address from the // transport out, else if any custom transport headers set on this message, or default // to the transport senders default From address if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) { if (log.isDebugEnabled()) { log.debug("Setting From header to " + outInfo.getFromAddress().getAddress() + " from OutTransportInfo"); } message.setFrom(outInfo.getFromAddress()); message.setReplyTo((new Address[] { outInfo.getFromAddress() })); } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) { InternetAddress from = new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM)); if (log.isDebugEnabled()) { log.debug("Setting From header to " + from.getAddress() + " from transport headers"); } message.setFrom(from); message.setReplyTo(new Address[] { from }); } else { if (smtpFromAddress != null) { if (log.isDebugEnabled()) { log.debug("Setting From header to " + smtpFromAddress.getAddress() + " from transport configuration"); } message.setFrom(smtpFromAddress); message.setReplyTo(new Address[] { smtpFromAddress }); } else { handleException("From address for outgoing message cannot be determined"); } } // set To address/es to any custom transport header set on the message, else use the reply // address from the out transport information if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) { Address[] to = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO)); if (log.isDebugEnabled()) { log.debug("Setting To header to " + InternetAddress.toString(to) + " from transport headers"); } message.setRecipients(Message.RecipientType.TO, to); } else if (outInfo.getTargetAddresses() != null) { if (log.isDebugEnabled()) { log.debug("Setting To header to " + InternetAddress.toString(outInfo.getTargetAddresses()) + " from OutTransportInfo"); } message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses()); } else { handleException("To address for outgoing message cannot be determined"); } // set Cc address/es to any custom transport header set on the message, else use the // Cc list from original request message if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) { Address[] cc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC)); if (log.isDebugEnabled()) { log.debug("Setting Cc header to " + InternetAddress.toString(cc) + " from transport headers"); } message.setRecipients(Message.RecipientType.CC, cc); } else if (outInfo.getCcAddresses() != null) { if (log.isDebugEnabled()) { log.debug("Setting Cc header to " + InternetAddress.toString(outInfo.getCcAddresses()) + " from OutTransportInfo"); } message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses()); } // set Bcc address/es to any custom addresses set at the transport sender level + any // custom transport header if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) { InternetAddress[] bcc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC)); if (log.isDebugEnabled()) { log.debug("Adding Bcc header values " + InternetAddress.toString(bcc) + " from transport headers"); } message.addRecipients(Message.RecipientType.BCC, bcc); } if (smtpBccAddresses != null) { if (log.isDebugEnabled()) { log.debug("Adding Bcc header values " + InternetAddress.toString(smtpBccAddresses) + " from transport configuration"); } message.addRecipients(Message.RecipientType.BCC, smtpBccAddresses); } // set subject if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) { if (log.isDebugEnabled()) { log.debug("Setting Subject header to '" + trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT) + "' from transport headers"); } message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)); } else if (outInfo.getSubject() != null) { if (log.isDebugEnabled()) { log.debug("Setting Subject header to '" + outInfo.getSubject() + "' from transport headers"); } message.setSubject(outInfo.getSubject()); } else { if (log.isDebugEnabled()) { log.debug("Generating default Subject header from SOAP action"); } message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction()); } //TODO: use a combined message id for smtp so that it generates a unique id while // being able to support asynchronous communication. // if a custom message id is set, use it // if (msgContext.getMessageID() != null) { // message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID()); // message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID()); // } // if this is a reply, set reference to original message if (outInfo.getRequestMessageID() != null) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID()); message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID()); } else { if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO)); } if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) { message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES)); } } // set Date message.setSentDate(new Date()); // set SOAPAction header message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); // write body MessageFormatterEx messageFormatterEx; if (messageFormatter instanceof MessageFormatterEx) { messageFormatterEx = (MessageFormatterEx) messageFormatter; } else { messageFormatterEx = new MessageFormatterExAdapter(messageFormatter); } DataHandler dataHandler = new DataHandler( messageFormatterEx.getDataSource(msgContext, format, msgContext.getSoapAction())); MimeMultipart mimeMultiPart = null; String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT); if (mFormat == null) { mFormat = defaultMailFormat; } if (log.isDebugEnabled()) { log.debug("Using mail format '" + mFormat + "'"); } MimePart mainPart; if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) { mimeMultiPart = new MimeMultipart(); MimeBodyPart mimeBodyPart1 = new MimeBodyPart(); mimeBodyPart1.setContent("Web Service Message Attached", "text/plain"); MimeBodyPart mimeBodyPart2 = new MimeBodyPart(); mimeMultiPart.addBodyPart(mimeBodyPart1); mimeMultiPart.addBodyPart(mimeBodyPart2); message.setContent(mimeMultiPart); mainPart = mimeBodyPart2; } else if (MailConstants.TRANSPORT_FORMAT_ATTACHMENT.equals(mFormat)) { mimeMultiPart = new MimeMultipart(); MimeBodyPart mimeBodyPart1 = new MimeBodyPart(); mimeBodyPart1.setContent("Web Service Message Attached", "text/plain"); MimeBodyPart mimeBodyPart2 = new MimeBodyPart(); mimeMultiPart.addBodyPart(mimeBodyPart1); mimeMultiPart.addBodyPart(mimeBodyPart2); message.setContent(mimeMultiPart); String fileName = (String) msgContext.getProperty(MailConstants.TRANSPORT_FORMAT_ATTACHMENT_FILE); if (fileName != null) { mimeBodyPart2.setFileName(fileName); } else { mimeBodyPart2.setFileName("attachment"); } mainPart = mimeBodyPart2; } else { mainPart = message; } try { mainPart.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); mainPart.setDataHandler(dataHandler); // AXIOM's idea of what is textual also includes application/xml and // application/soap+xml (which JavaMail considers as binary). For these content types // always use quoted-printable transfer encoding. Note that JavaMail is a bit smarter // here because it can choose between 7bit and quoted-printable automatically, but it // needs to scan the entire content to determine this. if (msgContext.getOptions().getProperty("Content-Transfer-Encoding") != null) { mainPart.setHeader("Content-Transfer-Encoding", (String) msgContext.getOptions().getProperty("Content-Transfer-Encoding")); } else { String contentType = dataHandler.getContentType().toLowerCase(); if (!contentType.startsWith("multipart/") && CommonUtils.isTextualPart(contentType)) { mainPart.setHeader("Content-Transfer-Encoding", "quoted-printable"); } } //setting any custom headers defined by the user if (msgContext.getOptions().getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS) != null) { Map customTransportHeaders = (Map) msgContext.getOptions() .getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS); for (Object header : customTransportHeaders.keySet()) { mainPart.setHeader((String) header, (String) customTransportHeaders.get(header)); } } log.debug("Sending message"); Transport.send(message); // update metrics metrics.incrementMessagesSent(msgContext); long bytesSent = message.getBytesSent(); if (bytesSent != -1) { metrics.incrementBytesSent(msgContext, bytesSent); } } catch (MessagingException e) { metrics.incrementFaultsSending(); handleException("Error creating mail message or sending it to the configured server", e); } return message.getMessageID(); }
From source file:com.openkm.util.MailUtils.java
/** * Create a mail./*from ww w . ja v a 2s . co m*/ * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null && Config.SEND_MAIL_FROM_USER) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:com.photon.phresco.util.Utility.java
public static void sendTemplateEmail(String[] toAddr, String fromAddr, String user, String subject, String body, String username, String password, String host, String screen, String build) throws PhrescoException { List<String> lists = Arrays.asList(toAddr); if (fromAddr == null) { fromAddr = "phresco.do.not.reply@gmail.com"; username = "phresco.do.not.reply@gmail.com"; password = "phresco123"; }//w w w. java 2s .c o m Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getDefaultInstance(props, new LoginAuthenticator(username, password)); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddr)); List<Address> emailsList = getEmailsList(lists); Address[] dsf = new Address[emailsList.size()]; message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf)); message.setSubject(subject); DataSource source = new FileDataSource(body); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName("Error.txt"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); MimeBodyPart messageBodyPart2 = new MimeBodyPart(); DataSource source2 = new FileDataSource(screen); messageBodyPart2.setDataHandler(new DataHandler(source2)); messageBodyPart2.setFileName("Error.jpg"); multipart.addBodyPart(messageBodyPart2); MimeBodyPart mainPart = new MimeBodyPart(); String content = "<b>Phresco framework error report<br><br>User Name: " + user + "<br> Email Address: " + fromAddr + "<br>Build No: " + build; mainPart.setContent(content, "text/html"); multipart.addBodyPart(mainPart); message.setContent(multipart); Transport.send(message); } catch (MessagingException e) { throw new PhrescoException(e); } }
From source file:org.j2free.email.EmailService.java
private void send(InternetAddress from, InternetAddress[] recipients, String subject, String body, ContentType contentType, Priority priority, boolean ccSender) throws AddressException, MessagingException, RejectedExecutionException { MimeMessage message = new MimeMessage(session); message.setFrom(from);/*from w w w .j ava2 s .c o m*/ message.setRecipients(Message.RecipientType.TO, recipients); for (Map.Entry<String, String> header : headers.entrySet()) message.setHeader(header.getKey(), header.getValue()); // CC the sender if they want if (ccSender) message.addRecipient(Message.RecipientType.CC, from); message.setReplyTo(new InternetAddress[] { from }); message.setSubject(subject); message.setSentDate(new Date()); if (contentType == ContentType.PLAIN) { // Just set the body as plain text message.setText(body, "UTF-8"); } else { MimeMultipart multipart = new MimeMultipart("alternative"); // Create the text part MimeBodyPart text = new MimeBodyPart(); text.setText(new HtmlFilter().filterForEmail(body), "UTF-8"); // Add the text part multipart.addBodyPart(text); // Create the HTML portion MimeBodyPart html = new MimeBodyPart(); html.setContent(body, ContentType.HTML.toString()); // Add the HTML portion multipart.addBodyPart(html); // set the message content message.setContent(multipart); } enqueue(message, priority); }
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
@Override public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body) throws DispositionReportFaultMessage, RemoteException { try {/*from w w w. j a v a2 s. c o m*/ log.info("Sending notification email to " + notificationEmailAddress + " from " + getEMailProperties().getProperty("mail.smtp.from", "jUDDI")); if (session != null && notificationEmailAddress != null) { MimeMessage message = new MimeMessage(session); InternetAddress address = new InternetAddress(notificationEmailAddress); Address[] to = { address }; message.setRecipients(RecipientType.TO, to); message.setFrom(new InternetAddress(getEMailProperties().getProperty("mail.smtp.from", "jUDDI"))); //maybe nice to use a template rather then sending raw xml. String subscriptionResultXML = JAXBMarshaller.marshallToString(body, JAXBMarshaller.PACKAGE_SUBSCR_RES); Multipart mp = new MimeMultipart(); MimeBodyPart content = new MimeBodyPart(); String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.body"); msg_content = String .format(msg_content, StringEscapeUtils.escapeHtml(this.publisherName), StringEscapeUtils.escapeHtml(AppConfig.getConfiguration() .getString(Property.JUDDI_NODE_ID, "(unknown node id!)")), GetSubscriptionType(body), GetChangeSummary(body)); content.setContent(msg_content, "text/html; charset=UTF-8;"); mp.addBodyPart(content); MimeBodyPart attachment = new MimeBodyPart(); attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;"); attachment.setFileName("uddiNotification.xml"); mp.addBodyPart(attachment); message.setContent(mp); message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " " + body.getSubscriptionResultsList().getSubscription().getSubscriptionKey()); Transport.send(message); } else { throw new DispositionReportFaultMessage("Session is null!", null); } } catch (Exception e) { log.error(e.getMessage(), e); throw new DispositionReportFaultMessage(e.getMessage(), null); } DispositionReport dr = new DispositionReport(); Result res = new Result(); dr.getResult().add(res); return dr; }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!/*from w ww.java 2 s . c om*/ * * @param multipart DOCUMENT ME! * @param text DOCUMENT ME! * @param charset DOCUMENT ME! * @param disposition DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static void attach(MimeMultipart multipart, String text, String charset, String disposition, boolean isHtml) throws MessagingException { int xid = multipart.getCount() + 1; MimeBodyPart xbody = new MimeBodyPart(); String xname = null; if (isHtml) { xname = "HTML" + xid + ".html"; xbody.setContent(text, "text/html" + "; charset=" + charset); xbody.setDescription("Html Attachment: " + xname, charset); } else { xname = "TEXT" + xid + ".txt"; xbody.setText(text, charset); xbody.setDescription("Text Attachment: " + xname, charset); } // UNDONE //xbody.setContentLanguage( String ); // this could be language from Locale //xbody.setContentMD5( String md5 ); // don't know about this yet xbody.setDisposition(disposition); MessageUtilities.setFileName(xbody, xname, charset); multipart.addBodyPart(xbody); }