List of usage examples for javax.mail.internet MimeBodyPart setContent
@Override public void setContent(Object o, String type) throws MessagingException
From source file:org.georchestra.console.ws.emails.EmailController.java
/** * Send EmailEntry to smtp server//www .ja va2s . com * * @param email email to send * @throws NameNotFoundException if recipient cannot be found in LDAP server * @throws DataServiceException if LDAP server is not available * @throws MessagingException if some field of email cannot be encoded (malformed email address) */ private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException { final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost()); session.getProperties().setProperty("mail.smtp.port", (new Integer(this.emailFactory.getSmtpPort())).toString()); final MimeMessage message = new MimeMessage(session); Account recipient = this.accountDao.findByUID(email.getRecipient()); InternetAddress[] senders = { new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) }; message.addFrom(senders); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail())); message.setSubject(email.getSubject()); message.setHeader("Date", (new MailDateFormat()).format(email.getDate())); // Mail content Multipart multiPart = new MimeMultipart("alternative"); // attachments for (Attachment att : email.getAttachments()) { MimeBodyPart mbp = new MimeBodyPart(); mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType()))); mbp.setFileName(att.getName()); multiPart.addBodyPart(mbp); } // html part MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(email.getBody(), "text/html; charset=utf-8"); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); // Send message Transport.send(message); }
From source file:voldemort.coordinator.HttpGetRequestExecutor.java
public void writeResponse(List<Versioned<byte[]>> versionedValues) throws Exception { MimeMultipart multiPart = new MimeMultipart(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (Versioned<byte[]> versionedValue : versionedValues) { byte[] responseValue = versionedValue.getValue(); VectorClock vectorClock = (VectorClock) versionedValue.getVersion(); String serializedVectorClock = CoordinatorUtils.getSerializedVectorClock(vectorClock); // Create the individual body part for each versioned value of the // requested key MimeBodyPart body = new MimeBodyPart(); try {/* www.j a va 2 s. c om*/ // Add the right headers body.addHeader(CONTENT_TYPE, "application/octet-stream"); body.addHeader(CONTENT_TRANSFER_ENCODING, "binary"); body.addHeader(VoldemortHttpRequestHandler.X_VOLD_VECTOR_CLOCK, serializedVectorClock); body.setContent(responseValue, "application/octet-stream"); body.addHeader(CONTENT_LENGTH, "" + responseValue.length); multiPart.addBodyPart(body); } catch (MessagingException me) { logger.error("Exception while constructing body part", me); outputStream.close(); throw me; } } try { multiPart.writeTo(outputStream); } catch (Exception e) { logger.error("Exception while writing multipart to output stream", e); outputStream.close(); throw e; } ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer(); responseContent.writeBytes(outputStream.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()); if (logger.isDebugEnabled()) { logger.debug("Response = " + response); } // Update the stats if (this.coordinatorPerfStats != null) { long durationInNs = System.nanoTime() - startTimestampInNs; this.coordinatorPerfStats.recordTime(Tracked.GET, durationInNs); } // Write the response to the Netty Channel this.getRequestMessageEvent.getChannel().write(response); }
From source file:org.apache.james.transport.mailets.DSNBounce.java
private MimeBodyPart createAttachedOriginal(Mail originalMail, TypeCode attachmentType) throws MessagingException { MimeBodyPart part = new MimeBodyPart(); MimeMessage originalMessage = originalMail.getMessage(); if (attachmentType.equals(TypeCode.HEADS)) { part.setContent(new MimeMessageUtils(originalMessage).getMessageHeaders(), "text/plain"); part.setHeader("Content-Type", "text/rfc822-headers"); } else {/*from w w w . j av a 2 s . c om*/ part.setContent(originalMessage, "message/rfc822"); } if ((originalMessage.getSubject() != null) && (originalMessage.getSubject().trim().length() > 0)) { part.setFileName(originalMessage.getSubject().trim()); } else { part.setFileName("No Subject"); } part.setDisposition("Attachment"); return part; }
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
public static void notifyAccountDeleted(TemporaryMailContainer container) { try {// w ww .j a v a 2 s . co m Publisher publisher = container.getPublisher(); Publisher deletedBy = container.getDeletedBy(); String emailaddress = publisher.getEmailAddress(); if (emailaddress == null || emailaddress.trim().equals("")) return; Properties properties = new Properties(); Session session = null; String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX, Property.DEFAULT_JUDDI_EMAIL_PREFIX); if (!mailPrefix.endsWith(".")) { mailPrefix = mailPrefix + "."; } for (String key : mailProps) { if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) { properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key)); } else if (System.getProperty(mailPrefix + key) != null) { properties.put(key, System.getProperty(mailPrefix + key)); } } boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true"); if (auth) { final String username = properties.getProperty("mail.smtp.user"); String pwd = properties.getProperty("mail.smtp.password"); //decrypt if possible if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false") .equalsIgnoreCase("true")) { try { pwd = CryptorFactory.getCryptor().decrypt(pwd); } catch (NoSuchPaddingException ex) { log.error("Unable to decrypt settings", ex); } catch (NoSuchAlgorithmException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidAlgorithmParameterException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidKeyException ex) { log.error("Unable to decrypt settings", ex); } catch (IllegalBlockSizeException ex) { log.error("Unable to decrypt settings", ex); } catch (BadPaddingException ex) { log.error("Unable to decrypt settings", ex); } } final String password = pwd; log.debug("SMTP username = " + username + " from address = " + emailaddress); Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(eMailProperties); } MimeMessage message = new MimeMessage(session); InternetAddress address = new InternetAddress(emailaddress); Address[] to = { address }; message.setRecipients(RecipientType.TO, to); message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI"))); //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s Multipart mp = new MimeMultipart(); MimeBodyPart content = new MimeBodyPart(); String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ"); //Hello %s, %s,<br><br>Your account has been deleted by %s, %s at %s. This node is %s. msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()), StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()), StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()), StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()), StringEscapeUtils.escapeHtml(sdf.format(new Date())), StringEscapeUtils.escapeHtml( AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)")); content.setContent(msg_content, "text/html; charset=UTF-8;"); mp.addBodyPart(content); message.setContent(mp); message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.accountDeleted.subject")); Transport.send(message); } catch (Throwable t) { log.warn("Error sending email!" + t.getMessage()); log.debug("Error sending email!" + t.getMessage(), t); } }
From source file:org.apache.synapse.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// w w w .java2 s . c om */ private void sendMail(MailOutTransportInfo outInfo, MessageContext msgContext) throws AxisFault, MessagingException, IOException { OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = null; try { messageFormatter = TransportUtils.getMessageFormatter(msgContext); } catch (AxisFault axisFault) { throw new BaseTransportException("Unable to get the message formatter to use"); } WSMimeMessage message = new WSMimeMessage(session); Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); // 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) { message.setFrom(outInfo.getFromAddress()); message.setReplyTo((new Address[] { outInfo.getFromAddress() })); } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) { message.setFrom(new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); message.setReplyTo(InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM))); } else { if (smtpFromAddress != null) { 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)) { message.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO))); } else if (outInfo.getTargetAddresses() != null) { 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)) { message.setRecipients(Message.RecipientType.CC, InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC))); } else if (outInfo.getTargetAddresses() != null) { 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 InternetAddress[] trpBccArr = null; if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) { trpBccArr = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC)); } InternetAddress[] mergedBcc = new InternetAddress[(trpBccArr != null ? trpBccArr.length : 0) + (smtpBccAddresses != null ? smtpBccAddresses.length : 0)]; if (trpBccArr != null) { System.arraycopy(trpBccArr, 0, mergedBcc, 0, trpBccArr.length); } if (smtpBccAddresses != null) { System.arraycopy(smtpBccAddresses, 0, mergedBcc, mergedBcc.length, smtpBccAddresses.length); } if (mergedBcc != null) { message.setRecipients(Message.RecipientType.BCC, mergedBcc); } // set subject if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) { message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)); } else if (outInfo.getSubject() != null) { message.setSubject(outInfo.getSubject()); } else { message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction()); } // 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 ByteArrayOutputStream baos = null; String contentType = messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()); DataHandler dataHandler = null; MimeMultipart mimeMultiPart = null; OMElement firstChild = msgContext.getEnvelope().getBody().getFirstElement(); if (firstChild != null) { if (BaseConstants.DEFAULT_BINARY_WRAPPER.equals(firstChild.getQName())) { baos = new ByteArrayOutputStream(); OMNode omNode = firstChild.getFirstOMChild(); if (omNode != null && omNode instanceof OMText) { Object dh = ((OMText) omNode).getDataHandler(); if (dh != null && dh instanceof DataHandler) { dataHandler = (DataHandler) dh; } } } else if (BaseConstants.DEFAULT_TEXT_WRAPPER.equals(firstChild.getQName())) { if (firstChild instanceof OMSourcedElementImpl) { baos = new ByteArrayOutputStream(); try { firstChild.serializeAndConsume(baos); } catch (XMLStreamException e) { handleException("Error serializing 'text' payload from OMSourcedElement", e); } dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()), MailConstants.TEXT_PLAIN); } else { dataHandler = new DataHandler(firstChild.getText(), MailConstants.TEXT_PLAIN); } } else { baos = new ByteArrayOutputStream(); messageFormatter.writeTo(msgContext, format, baos, true); // create the data handler dataHandler = new DataHandler(new String(baos.toByteArray(), format.getCharSetEncoding()), contentType); String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT); if (mFormat == null) { mFormat = defaultMailFormat; } 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(); mimeBodyPart2.setDataHandler(dataHandler); mimeBodyPart2.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); mimeMultiPart.addBodyPart(mimeBodyPart1); mimeMultiPart.addBodyPart(mimeBodyPart2); } else { message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); } } } try { if (mimeMultiPart == null) { message.setDataHandler(dataHandler); } else { message.setContent(mimeMultiPart); } Transport.send(message); } catch (MessagingException e) { handleException("Error creating mail message or sending it to the configured server", e); } finally { try { if (baos != null) { baos.close(); } } catch (IOException ignore) { } } }
From source file:org.pentaho.platform.plugin.action.builtin.EmailComponent.java
@Override public boolean executeAction() { EmailAction emailAction = (EmailAction) getActionDefinition(); String messagePlain = emailAction.getMessagePlain().getStringValue(); String messageHtml = emailAction.getMessageHtml().getStringValue(); String subject = emailAction.getSubject().getStringValue(); String to = emailAction.getTo().getStringValue(); String cc = emailAction.getCc().getStringValue(); String bcc = emailAction.getBcc().getStringValue(); String from = emailAction.getFrom().getStringValue(defaultFrom); if (from.trim().length() == 0) { from = defaultFrom;//from www .j a v a2 s . c o m } /* * if( context.getInputNames().contains( "attach" ) ) { //$NON-NLS-1$ Object attachParameter = * context.getInputParameter( "attach" ).getValue(); //$NON-NLS-1$ // We have a list of attachments, each element of * the list is the name of the parameter containing the attachment // Use the parameter filename portion as the * attachment name. if ( attachParameter instanceof String ) { String attachName = context.getInputParameter( * "attach-name" ).getStringValue(); //$NON-NLS-1$ AttachStruct attachData = getAttachData( context, * (String)attachParameter, attachName ); if ( attachData != null ) { attachments.add( attachData ); } } else if ( * attachParameter instanceof List ) { for ( int i = 0; i < ((List)attachParameter).size(); ++i ) { AttachStruct * attachData = getAttachData( context, ((List)attachParameter).get( i ).toString(), null ); if ( attachData != null * ) { attachments.add( attachData ); } } } else if ( attachParameter instanceof Map ) { for ( Iterator it = * ((Map)attachParameter).entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next(); * AttachStruct attachData = getAttachData( context, (String)entry.getValue(), (String)entry.getKey() ); if ( * attachData != null ) { attachments.add( attachData ); } } } } * * int maxSize = Integer.MAX_VALUE; try { maxSize = new Integer( props.getProperty( "mail.max.attach.size" ) * ).intValue(); } catch( Throwable t ) { //ignore if not set to a valid value } * * if ( totalAttachLength > maxSize ) { // Sort them in order TreeMap tm = new TreeMap(); for( int idx=0; * idx<attachments.size(); idx++ ) { // tm.put( new Integer( )) } } */ if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain)); //$NON-NLS-1$ debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml)); //$NON-NLS-1$ } if ((to == null) || (to.trim().length() == 0)) { // Get the output stream that the feedback is going into OutputStream feedbackStream = getFeedbackOutputStream(); if (feedbackStream != null) { createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), //$NON-NLS-1$//$NON-NLS-2$ "", "", true); //$NON-NLS-1$ //$NON-NLS-2$ setFeedbackMimeType("text/html"); //$NON-NLS-1$ return true; } else { return false; } } if (subject == null) { error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName())); //$NON-NLS-1$ return false; } if ((messagePlain == null) && (messageHtml == null)) { error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName())); //$NON-NLS-1$ return false; } if (getRuntimeContext().isPromptPending()) { return true; } try { Properties props = new Properties(); final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService", PentahoSessionHolder.getSession()); props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost()); props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort())); props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol()); props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls())); props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate())); props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl())); props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait())); props.put("mail.from.default", service.getEmailConfig().getDefaultFrom()); String fromName = service.getEmailConfig().getFromName(); if (StringUtils.isEmpty(fromName)) { fromName = Messages.getInstance().getString("schedulerEmailFromName"); } props.put("mail.from.name", fromName); props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug())); Session session; if (service.getEmailConfig().isAuthenticate()) { props.put("mail.userid", service.getEmailConfig().getUserId()); props.put("mail.password", service.getEmailConfig().getPassword()); Authenticator authenticator = new EmailAuthenticator(); session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } // debugging is on if either component (xaction) or email config debug is on if (service.getEmailConfig().isDebug() || ComponentBase.debug) { session.setDebug(true); } // construct the message MimeMessage msg = new MimeMessage(session); if (from != null) { msg.setFrom(new InternetAddress(from)); } else { // There should be no way to get here error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED")); //$NON-NLS-1$ } if ((to != null) && (to.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); } if ((cc != null) && (cc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); } if ((bcc != null) && (bcc.trim().length() > 0)) { msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); } if (subject != null) { msg.setSubject(subject, LocaleHelper.getSystemEncoding()); } EmailAttachment[] emailAttachments = emailAction.getAttachments(); if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) { msg.setText(messagePlain, LocaleHelper.getSystemEncoding()); } else if (emailAttachments.length == 0) { if (messagePlain != null) { msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ } if (messageHtml != null) { msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ } } else { // need to create a multi-part message... // create the Multipart and add its parts to it Multipart multipart = new MimeMultipart(); // create and fill the first message part if (messageHtml != null) { // create and fill the first message part MimeBodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(htmlBodyPart); } if (messagePlain != null) { MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$ multipart.addBodyPart(textBodyPart); } for (EmailAttachment element : emailAttachments) { IPentahoStreamSource source = element.getContent(); if (source == null) { error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED")); //$NON-NLS-1$ return false; } DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source); String attachmentName = element.getName(); if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName)); //$NON-NLS-1$ } // create the second message part MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // attach the file to the message attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(attachmentName); if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", //$NON-NLS-1$ dataSource.getName())); } multipart.addBodyPart(attachmentBodyPart); } // add the Multipart to the message msg.setContent(multipart); } msg.setHeader("X-Mailer", EmailComponent.MAILER); //$NON-NLS-1$ msg.setSentDate(new Date()); Transport.send(msg); if (ComponentBase.debug) { debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS")); //$NON-NLS-1$ } return true; // TODO: persist the content set for a while... } catch (SendFailedException e) { error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$ /* * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof * MessagingException) { sfe = (MessagingException) ne; * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe); * //$NON-NLS-1$ } */ } catch (AuthenticationFailedException e) { error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e); //$NON-NLS-1$ } catch (Throwable e) { error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$ } return false; }
From source file:com.threewks.thundr.gmail.GmailMailer.java
protected void populateMimeBodyPart(MimeBodyPart mimeBodyPart, Attachment attachment, byte[] data, String attachmentContentType, String attachmentCharacterEncoding) throws MessagingException { String fullContentType = attachmentContentType + "; charset=" + attachmentCharacterEncoding; mimeBodyPart.setFileName(attachment.name()); mimeBodyPart.setContent(data, fullContentType); mimeBodyPart.setDisposition(attachment.disposition().toString()); if (attachment.isInline()) { mimeBodyPart.setContentID("<" + attachment.name() + ">"); }/* w w w. j a va 2 s . c o m*/ }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail./* w w w . java 2s .c o 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) { 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:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
public static void notifySubscriptionDeleted(TemporaryMailContainer container) { try {//w w w. ja v a2s.c om Publisher publisher = container.getPublisher(); Publisher deletedBy = container.getDeletedBy(); Subscription obj = container.getObj(); String emailaddress = publisher.getEmailAddress(); if (emailaddress == null || emailaddress.trim().equals("")) return; Properties properties = new Properties(); Session session = null; String mailPrefix = AppConfig.getConfiguration().getString(Property.JUDDI_EMAIL_PREFIX, Property.DEFAULT_JUDDI_EMAIL_PREFIX); if (!mailPrefix.endsWith(".")) { mailPrefix = mailPrefix + "."; } for (String key : mailProps) { if (AppConfig.getConfiguration().containsKey(mailPrefix + key)) { properties.put(key, AppConfig.getConfiguration().getProperty(mailPrefix + key)); } else if (System.getProperty(mailPrefix + key) != null) { properties.put(key, System.getProperty(mailPrefix + key)); } } boolean auth = (properties.getProperty("mail.smtp.auth", "false")).equalsIgnoreCase("true"); if (auth) { final String username = properties.getProperty("mail.smtp.user"); String pwd = properties.getProperty("mail.smtp.password"); //decrypt if possible if (properties.getProperty("mail.smtp.password" + Property.ENCRYPTED_ATTRIBUTE, "false") .equalsIgnoreCase("true")) { try { pwd = CryptorFactory.getCryptor().decrypt(pwd); } catch (NoSuchPaddingException ex) { log.error("Unable to decrypt settings", ex); } catch (NoSuchAlgorithmException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidAlgorithmParameterException ex) { log.error("Unable to decrypt settings", ex); } catch (InvalidKeyException ex) { log.error("Unable to decrypt settings", ex); } catch (IllegalBlockSizeException ex) { log.error("Unable to decrypt settings", ex); } catch (BadPaddingException ex) { log.error("Unable to decrypt settings", ex); } } final String password = pwd; log.debug("SMTP username = " + username + " from address = " + emailaddress); Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); } else { Properties eMailProperties = properties; eMailProperties.remove("mail.smtp.user"); eMailProperties.remove("mail.smtp.password"); session = Session.getInstance(eMailProperties); } MimeMessage message = new MimeMessage(session); InternetAddress address = new InternetAddress(emailaddress); Address[] to = { address }; message.setRecipients(RecipientType.TO, to); message.setFrom(new InternetAddress(properties.getProperty("mail.smtp.from", "jUDDI"))); //Hello %s,<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s //maybe nice to use a template rather then sending raw xml. org.uddi.sub_v3.Subscription api = new org.uddi.sub_v3.Subscription(); MappingModelToApi.mapSubscription(obj, api); String subscriptionResultXML = JAXBMarshaller.marshallToString(api, JAXBMarshaller.PACKAGE_SUBSCR_RES); Multipart mp = new MimeMultipart(); MimeBodyPart content = new MimeBodyPart(); String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.subscriptionDeleted"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ssZ"); //Hello %s, %s<br><br>Your subscription UDDI subscription was deleted. Attached is what the subscription was. It was deleted by %s, %s at %s. This node is %s. msg_content = String.format(msg_content, StringEscapeUtils.escapeHtml(publisher.getPublisherName()), StringEscapeUtils.escapeHtml(publisher.getAuthorizedName()), StringEscapeUtils.escapeHtml(deletedBy.getPublisherName()), StringEscapeUtils.escapeHtml(deletedBy.getAuthorizedName()), StringEscapeUtils.escapeHtml(sdf.format(new Date())), StringEscapeUtils.escapeHtml( AppConfig.getConfiguration().getString(Property.JUDDI_NODE_ID, "(unknown node id!)")), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL, "(unknown url)"), AppConfig.getConfiguration().getString(Property.JUDDI_BASE_URL_SECURE, "(unknown url)")); 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") + " " + StringEscapeUtils.escapeHtml(obj.getSubscriptionKey())); Transport.send(message); } catch (Throwable t) { log.warn("Error sending email!" + t.getMessage()); log.debug("Error sending email!" + t.getMessage(), t); } }
From source file:org.etudes.jforum.util.mail.Spammer.java
/** * prepare attachment message//ww w.j av a2s. co m * @param addresses Addresses * @param params Message params * @param subject Message subject * @param messageFile Message file * @param attachments Attachments * @throws EmailException */ protected final void prepareAttachmentMessage(List addresses, SimpleHash params, String subject, String messageFile, List attachments) throws EmailException { if (logger.isDebugEnabled()) logger.debug("prepareAttachmentMessage with attachments entering....."); this.message = new MimeMessage(session); try { InternetAddress[] recipients = new InternetAddress[addresses.size()]; String charset = SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET); this.message.setSentDate(new Date()); // this.message.setFrom(new InternetAddress(SystemGlobals.getValue(ConfigKeys.MAIL_SENDER))); String from = "\"" + ServerConfigurationService.getString("ui.service", "Sakai") + "\"<no-reply@" + ServerConfigurationService.getServerName() + ">"; this.message.setFrom(new InternetAddress(from)); this.message.setSubject(subject, charset); this.messageText = this.getMessageText(params, messageFile); MimeBodyPart messageBodyPart = new MimeBodyPart(); String messagetype = ""; // message if (messageFormat == MESSAGE_HTML) { messagetype = "text/html; charset=" + charset; messageBodyPart.setContent(this.messageText, messagetype); } else { messagetype = "text/plain; charset=" + charset; messageBodyPart.setContent(this.messageText, messagetype); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // attachments Attachment attachment = null; Iterator iterAttach = attachments.iterator(); while (iterAttach.hasNext()) { attachment = (Attachment) iterAttach.next(); // String filePath = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + attachment.getInfo().getPhysicalFilename(); String filePath = SakaiSystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/" + attachment.getInfo().getPhysicalFilename(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filePath); try { messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getInfo().getRealFilename()); multipart.addBodyPart(messageBodyPart); } catch (MessagingException e) { if (logger.isWarnEnabled()) logger.warn("Error while attaching attachments in prepareAttachmentMessage(...) : " + e); } } message.setContent(multipart); int i = 0; for (Iterator iter = addresses.iterator(); iter.hasNext(); i++) { recipients[i] = new InternetAddress((String) iter.next()); } this.message.setRecipients(Message.RecipientType.TO, recipients); } catch (Exception e) { logger.warn(e); throw new EmailException(e); } if (logger.isDebugEnabled()) logger.debug("prepareAttachmentMessage with attachments exiting....."); }