List of usage examples for javax.mail MessagingException MessagingException
public MessagingException(String s)
From source file:org.dspace.app.webui.servlet.SuggestServlet.java
protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, AuthorizeException { // Obtain information from request // The page where the user came from String fromPage = request.getHeader("Referer"); // Prevent spammers and splogbots from poisoning the feedback page String host = ConfigurationManager.getProperty("dspace.hostname"); String basicHost = ""; if (host.equals("localhost") || host.equals("127.0.0.1") || host.equals(InetAddress.getLocalHost().getHostAddress())) { basicHost = host;/*w w w . j ava2 s.co m*/ } else { // cut off all but the hostname, to cover cases where more than one URL // arrives at the installation; e.g. presence or absence of "www" int lastDot = host.lastIndexOf('.'); basicHost = host.substring(host.substring(0, lastDot).lastIndexOf(".")); } if (fromPage == null || fromPage.indexOf(basicHost) == -1) { throw new AuthorizeException(); } // Obtain information from request String handle = request.getParameter("handle"); // Lookup Item title & collection String title = null; String collName = null; if (handle != null && !handle.equals("")) { Item item = (Item) HandleManager.resolveToObject(context, handle); if (item != null) { DCValue[] titleDC = item.getDC("title", null, Item.ANY); if (titleDC != null && titleDC.length > 0) { title = titleDC[0].value; } Collection[] colls = item.getCollections(); collName = colls[0].getMetadata("name"); } } else { String path = request.getPathInfo(); log.info(LogManager.getHeader(context, "invalid_id", "path=" + path)); JSPManager.showInvalidIDError(request, response, path, -1); return; } if (title == null) { title = ""; } if (collName == null) { collName = ""; } request.setAttribute("suggest.title", title); // User email from context EPerson currentUser = context.getCurrentUser(); String authEmail = null; String userName = null; if (currentUser != null) { authEmail = currentUser.getEmail(); userName = currentUser.getFullName(); } if (request.getParameter("submit") != null) { String recipAddr = request.getParameter("recip_email"); // the only required field is recipient email address if (recipAddr == null || recipAddr.equals("")) { log.info(LogManager.getHeader(context, "show_suggest_form", "problem=true")); request.setAttribute("suggest.problem", Boolean.TRUE); JSPManager.showJSP(request, response, "/suggest/suggest.jsp"); return; } String recipName = request.getParameter("recip_name"); if (recipName == null || "".equals(recipName)) { try { recipName = I18nUtil.getMessage("org.dspace.app.webui.servlet.SuggestServlet.recipient", context); } catch (MissingResourceException e) { log.warn(LogManager.getHeader(context, "show_suggest_form", "Missing Resource: org.dspace.app.webui.servlet.SuggestServlet.sender")); recipName = "colleague"; } } String senderName = request.getParameter("sender_name"); if (senderName == null || "".equals(senderName)) { // use userName if available if (userName != null) { senderName = userName; } else { try { senderName = I18nUtil.getMessage("org.dspace.app.webui.servlet.SuggestServlet.sender", context); } catch (MissingResourceException e) { log.warn(LogManager.getHeader(context, "show_suggest_form", "Missing Resource: org.dspace.app.webui.servlet.SuggestServlet.sender")); senderName = "A DSpace User"; } } } String senderAddr = request.getParameter("sender_email"); if (StringUtils.isEmpty(senderAddr) && authEmail != null) { // use authEmail if available senderAddr = authEmail; } String itemUri = HandleManager.getCanonicalForm(handle); String itemUrl = HandleManager.resolveToURL(context, handle); String message = request.getParameter("message"); String siteName = ConfigurationManager.getProperty("dspace.name"); // All data is there, send the email try { Email email = ConfigurationManager .getEmail(I18nUtil.getEmailFilename(context.getCurrentLocale(), "suggest")); email.addRecipient(recipAddr); // recipient address email.addArgument(recipName); // 1st arg - recipient name email.addArgument(senderName); // 2nd arg - sender name email.addArgument(siteName); // 3rd arg - repository name email.addArgument(title); // 4th arg - item title email.addArgument(itemUri); // 5th arg - item handle URI email.addArgument(itemUrl); // 6th arg - item local URL email.addArgument(collName); // 7th arg - collection name email.addArgument(message); // 8th arg - user comments // Set sender's address as 'reply-to' address if supplied if (senderAddr != null && !"".equals(senderAddr)) { email.setReplyTo(senderAddr); } // Only actually send the email if feature is enabled if (ConfigurationManager.getBooleanProperty("webui.suggest.enable", false)) { email.send(); } else { throw new MessagingException("Suggest item email not sent - webui.suggest.enable = false"); } log.info(LogManager.getHeader(context, "sent_suggest", "from=" + senderAddr)); JSPManager.showJSP(request, response, "/suggest/suggest_ok.jsp"); } catch (MessagingException me) { log.warn(LogManager.getHeader(context, "error_mailing_suggest", ""), me); JSPManager.showInternalError(request, response); } } else { // Display suggest form log.info(LogManager.getHeader(context, "show_suggest_form", "problem=false")); request.setAttribute("authenticated.email", authEmail); request.setAttribute("eperson.name", userName); JSPManager.showJSP(request, response, "/suggest/suggest.jsp"); //asd } }
From source file:org.elasticsearch.river.email.EmailToJson.java
public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException { String from = ""; Address[] froms = msg.getFrom();/*from w w w . j ava2 s .c om*/ if (froms.length < 1) throw new MessagingException("?!"); InternetAddress address = (InternetAddress) froms[0]; String person = address.getPersonal(); if (person != null) { person = MimeUtility.decodeText(person) + " "; } else { person = ""; } from = person + "<" + address.getAddress() + ">"; return from; }
From source file:org.entermedia.email.PostMail.java
public void postMail(List<InternetAddress> recipients, List<InternetAddress> blindrecipients, String subject, String inHtml, String inText, String from, List inAttachments, Map inProperties) throws MessagingException { // Set the host smtp address Properties props = new Properties(); // create some properties and get the default Session props.put("mail.smtp.host", fieldSmtpServer); props.put("mail.smtp.port", String.valueOf(getPort())); props.put("mail.smtp.auth", new Boolean(fieldSmtpSecured).toString()); if (isSslEnabled()) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); }//from w ww.j av a2 s .c o m Session session = null; if (isEnableTls()) { props.put("mail.smtp.starttls.enable", "true"); session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(getSmtpUsername(), getSmtpPassword()); } }); } else if (fieldSmtpSecured) { SmtpAuthenticator auth = new SmtpAuthenticator(); session = Session.getInstance(props, auth); } else { session = Session.getInstance(props); } // session.setDebug(debug); // create a message Message msg = new MimeMessage(session); MimeMultipart mp = null; // msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, // "text/html"))); if (inAttachments != null && inAttachments.size() == 0) { inAttachments = null; } if (inText != null && inHtml != null || inAttachments != null) { // Create an "Alternative" Multipart message mp = new MimeMultipart("mixed"); if (inText != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(inText, "text/plain"); mp.addBodyPart(messageBodyPart); } if (inHtml != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(inHtml, "text/html"); mp.addBodyPart(messageBodyPart); } if (inAttachments != null) { for (Iterator iterator = inAttachments.iterator(); iterator.hasNext();) { String filename = (String) iterator.next(); File file = new File(filename); if (file.exists() && !file.isDirectory()) { // create the second message part MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(file); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); } } } msg.setContent(mp); } else if (inHtml != null) { msg.setContent(inHtml, "text/html"); } else { msg.setContent(inText, "text/plain"); } // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); //msg.setRecipient(RecipientType.BCC, addressFrom); msg.setSentDate(new Date()); if (recipients == null || recipients.isEmpty()) { throw new MessagingException("No recipients specified"); } InternetAddress[] addressTo = recipients.toArray(new InternetAddress[recipients.size()]); msg.setRecipients(Message.RecipientType.TO, addressTo); //add bcc if (blindrecipients != null && !blindrecipients.isEmpty()) { InternetAddress[] addressBcc = blindrecipients.toArray(new InternetAddress[blindrecipients.size()]); msg.setRecipients(Message.RecipientType.BCC, addressBcc); } // Optional : You can also set your custom headers in the Email if you // Want // msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject(subject); // Transport tr = session.getTransport("smtp"); // tr.connect(serverandport[0], null, null); // msg.saveChanges(); // don't forget this // tr.sendMessage(msg, msg.getAllRecipients()); // tr.close(); // msg.setContent(msg, "text/plain"); Transport.send(msg); log.info("sent email " + subject); }
From source file:org.jasig.ssp.service.impl.MessageServiceImpl.java
@Override @Transactional(readOnly = false)/*from w ww . ja v a 2 s .c o m*/ public boolean sendMessage(@NotNull final Message message) throws ObjectNotFoundException, SendFailedException, UnsupportedEncodingException { LOGGER.info("BEGIN : sendMessage()"); LOGGER.info(addMessageIdToError(message) + "Sending message: {}", message.toString()); try { final MimeMessage mimeMessage = javaMailSender.createMimeMessage(); final MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage); // process FROM addresses InternetAddress from; String appName = configService.getByName("app_title").getValue(); //We used the configured outbound email address for every outgoing message //If a message was initiated by an end user, their name will be attached to the 'from' while //the configured outbound address will be the actual address used for example "Amy Aministrator (SSP) <myconfiguredaddress@foobar.com>" String name = appName + " Administrator"; if (message.getSender() != null && !message.getSender().getEmailAddresses().isEmpty() && !message.getSender().getId().equals(Person.SYSTEM_ADMINISTRATOR_ID)) { InternetAddress[] froms = getEmailAddresses(message.getSender(), "from:", message.getId()); if (froms.length > 0) { name = message.getSender().getFullName() + " (" + appName + ")"; } } from = new InternetAddress(configService.getByName("outbound_email_address").getValue(), name); if (!this.validateEmail(from.getAddress())) { throw new AddressException("Invalid from: email address [" + from.getAddress() + "]"); } mimeMessageHelper.setFrom(from); message.setSentFromAddress(from.toString()); mimeMessageHelper.setReplyTo(from); message.setSentReplyToAddress(from.toString()); // process TO addresses InternetAddress[] tos = null; if (message.getRecipient() != null && message.getRecipient().hasEmailAddresses()) { // NOPMD by jon.adams tos = getEmailAddresses(message.getRecipient(), "to:", message.getId()); } else { tos = getEmailAddresses(message.getRecipientEmailAddress(), "to:", message.getId()); } if (tos.length > 0) { mimeMessageHelper.setTo(tos); message.setSentToAddresses(StringUtils.join(tos, ",").trim()); } else { StringBuilder errorMsg = new StringBuilder(); errorMsg.append(addMessageIdToError(message) + " Message " + message.toString() + " could not be sent. No valid recipient email address found: '"); if (message.getRecipient() != null) { errorMsg.append(message.getRecipient().getPrimaryEmailAddress()); } else { errorMsg.append(message.getRecipientEmailAddress()); } LOGGER.error(errorMsg.toString()); throw new MessagingException(errorMsg.toString()); } // process BCC addresses try { InternetAddress[] bccs = getEmailAddresses(getBcc(), "bcc:", message.getId()); if (bccs.length > 0) { mimeMessageHelper.setBcc(bccs); message.setSentBccAddresses(StringUtils.join(bccs, ",").trim()); } } catch (Exception exp) { LOGGER.warn("Unrecoverable errors were generated adding carbon copy to message: " + message.getId() + "Attempt to send message still initiated.", exp); } // process CC addresses try { InternetAddress[] carbonCopies = getEmailAddresses(message.getCarbonCopy(), "cc:", message.getId()); if (carbonCopies.length > 0) { mimeMessageHelper.setCc(carbonCopies); message.setSentCcAddresses(StringUtils.join(carbonCopies, ",").trim()); } } catch (Exception exp) { LOGGER.warn("Unrecoverable errors were generated adding bcc to message: " + message.getId() + "Attempt to send message still initiated.", exp); } mimeMessageHelper.setSubject(message.getSubject()); mimeMessageHelper.setText(message.getBody()); mimeMessage.setContent(message.getBody(), "text/html"); send(mimeMessage); message.setSentDate(new Date()); messageDao.save(message); } catch (final MessagingException e) { LOGGER.error("ERROR : sendMessage() : {}", e); handleSendMessageError(message); throw new SendFailedException(addMessageIdToError(message) + "The message parameters were invalid.", e); } LOGGER.info("END : sendMessage()"); return true; }
From source file:org.masukomi.aspirin.core.RemoteDelivery.java
/** * We can assume that the recipients of this message are all going to the * same mail server. We will now rely on the JNDI to do DNS MX record lookup * and try to deliver to the multiple mail servers. If it fails, it should * throw an exception.// w ww. j ava2 s . c o m * * Creation date: (2/24/00 11:25:00 PM) * * @param mail * org.apache.james.core.MailImpl * @param session * javax.mail.Session * @return boolean Whether the delivery was successful and the message can * be deleted */ private boolean deliver(QuedItem qi, Session session) { MailAddress rcpt = null; try { if (log.isDebugEnabled()) { log.debug("entering RemoteDelivery.deliver(QuedItem qi, Session session)"); } MailImpl mail = (MailImpl) qi.getMail(); MimeMessage message = mail.getMessage(); // Create an array of the recipients as InternetAddress objects Collection recipients = mail.getRecipients(); InternetAddress addr[] = new InternetAddress[recipients.size()]; int j = 0; // funky ass look because you can't getElementAt() in a Collection for (Iterator i = recipients.iterator(); i.hasNext(); j++) { MailAddress currentRcpt = (MailAddress) i.next(); addr[j] = currentRcpt.toInternetAddress(); } if (addr.length <= 0) { if (log.isDebugEnabled()) { log.debug("No recipients specified... returning"); } return true; } // Figure out which servers to try to send to. This collection // will hold all the possible target servers Collection targetServers = null; Iterator it = recipients.iterator(); while (it.hasNext()) { rcpt = (MailAddress) recipients.iterator().next(); if (!qi.recepientHasBeenHandled(rcpt)) { break; } } // theoretically it is possible to not hav eone that hasn't been // handled // however that's only if something has gone really wrong. if (rcpt != null) { String host = rcpt.getHost(); // Lookup the possible targets try { // targetServers = MXLookup.urlsForHost(host); // farking // unreliable jndi bs targetServers = getMXRecordsForHost(host); } catch (Exception e) { log.error(e); } if (targetServers == null || targetServers.size() == 0) { log.warn("No mail server found for: " + host); StringBuffer exceptionBuffer = new StringBuffer(128) .append("I found no MX record entries for the hostname ").append(host) .append(". I cannot determine where to send this message."); return failMessage(qi, rcpt, new MessagingException(exceptionBuffer.toString()), true); } else if (log.isTraceEnabled()) { log.trace(targetServers.size() + " servers found for " + host); } MessagingException lastError = null; Iterator i = targetServers.iterator(); while (i.hasNext()) { try { URLName outgoingMailServer = (URLName) i.next(); StringBuffer logMessageBuffer = new StringBuffer(256).append("Attempting delivery of ") .append(mail.getName()).append(" to host ").append(outgoingMailServer.toString()) .append(" to addresses ").append(Arrays.asList(addr)); if (log.isDebugEnabled()) { log.debug(logMessageBuffer.toString()); } ; // URLName urlname = new URLName("smtp://" // + outgoingMailServer); Properties props = session.getProperties(); if (mail.getSender() == null) { props.put("mail.smtp.from", "<>"); } else { String sender = mail.getSender().toString(); props.put("mail.smtp.from", sender); } // Many of these properties are only in later JavaMail // versions // "mail.smtp.ehlo" //default true // "mail.smtp.auth" //default false // "mail.smtp.dsn.ret" //default to nothing... appended // as // RET= after MAIL FROM line. // "mail.smtp.dsn.notify" //default to // nothing...appended as // NOTIFY= after RCPT TO line. Transport transport = null; try { transport = session.getTransport(outgoingMailServer); try { transport.connect(); } catch (MessagingException me) { log.error(me); // Any error on connect should cause the mailet // to // attempt // to connect to the next SMTP server associated // with this MX record, // assuming the number of retries hasn't been // exceeded. if (failMessage(qi, rcpt, me, false)) { return true; } else { continue; } } transport.sendMessage(message, addr); // log.debug("message sent to " +addr); /*TODO: catch failures that should result * in failure with no retries } catch (SendFailedException sfe){ qi.failForRecipient(que, ); */ } finally { if (transport != null) { transport.close(); transport = null; } } logMessageBuffer = new StringBuffer(256).append("Mail (").append(mail.getName()) .append(") sent successfully to ").append(outgoingMailServer); log.debug(logMessageBuffer.toString()); qi.succeededForRecipient(que, rcpt); return true; } catch (MessagingException me) { log.error(me); // MessagingException are horribly difficult to figure // out // what actually happened. StringBuffer exceptionBuffer = new StringBuffer(256) .append("Exception delivering message (").append(mail.getName()).append(") - ") .append(me.getMessage()); log.warn(exceptionBuffer.toString()); if ((me.getNextException() != null) && (me.getNextException() instanceof java.io.IOException)) { // This is more than likely a temporary failure // If it's an IO exception with no nested exception, // it's probably // some socket or weird I/O related problem. lastError = me; continue; } // This was not a connection or I/O error particular to // one // SMTP server of an MX set. Instead, it is almost // certainly // a protocol level error. In this case we assume that // this // is an error we'd encounter with any of the SMTP // servers // associated with this MX record, and we pass the // exception // to the code in the outer block that determines its // severity. throw me; } // end catch } // end while // If we encountered an exception while looping through, // throw the last MessagingException we caught. We only // do this if we were unable to send the message to any // server. If sending eventually succeeded, we exit // deliver() though the return at the end of the try // block. if (lastError != null) { throw lastError; } } // END if (rcpt != null) else { log.error("unable to find recipient that handn't already been handled"); } } catch (SendFailedException sfe) { log.error(sfe); boolean deleteMessage = false; Collection recipients = qi.getMail().getRecipients(); // Would like to log all the types of email addresses if (log.isDebugEnabled()) { log.debug("Recipients: " + recipients); } /* * The rest of the recipients failed for one reason or another. * * SendFailedException actually handles this for us. For example, if * you send a message that has multiple invalid addresses, you'll * get a top-level SendFailedException that that has the valid, * valid-unsent, and invalid address lists, with all of the server * response messages will be contained within the nested exceptions. * [Note: the content of the nested exceptions is implementation * dependent.] * * sfe.getInvalidAddresses() should be considered permanent. * sfe.getValidUnsentAddresses() should be considered temporary. * * JavaMail v1.3 properly populates those collections based upon the * 4xx and 5xx response codes. * */ if (sfe.getInvalidAddresses() != null) { Address[] address = sfe.getInvalidAddresses(); if (address.length > 0) { recipients.clear(); for (int i = 0; i < address.length; i++) { try { recipients.add(new MailAddress(address[i].toString())); } catch (ParseException pe) { // this should never happen ... we should have // caught malformed addresses long before we // got to this code. if (log.isDebugEnabled()) { log.debug("Can't parse invalid address: " + pe.getMessage()); } } } if (log.isDebugEnabled()) { log.debug("Invalid recipients: " + recipients); } deleteMessage = failMessage(qi, rcpt, sfe, true); } } if (sfe.getValidUnsentAddresses() != null) { Address[] address = sfe.getValidUnsentAddresses(); if (address.length > 0) { recipients.clear(); for (int i = 0; i < address.length; i++) { try { recipients.add(new MailAddress(address[i].toString())); } catch (ParseException pe) { // this should never happen ... we should have // caught malformed addresses long before we // got to this code. if (log.isDebugEnabled()) { log.debug("Can't parse unsent address: " + pe.getMessage()); } pe.printStackTrace(); } } if (log.isDebugEnabled()) { log.debug("Unsent recipients: " + recipients); } deleteMessage = failMessage(qi, rcpt, sfe, false); } } return deleteMessage; } catch (MessagingException ex) { log.error(ex); // We should do a better job checking this... if the failure is a // general // connect exception, this is less descriptive than more specific // SMTP command // failure... have to lookup and see what are the various Exception // possibilities // Unable to deliver message after numerous tries... fail // accordingly // We check whether this is a 5xx error message, which // indicates a permanent failure (like account doesn't exist // or mailbox is full or domain is setup wrong). // We fail permanently if this was a 5xx error return failMessage(qi, rcpt, ex, ('5' == ex.getMessage().charAt(0))); } catch (Throwable t) { log.error(t); } /* * If we get here, we've exhausted the loop of servers without sending * the message or throwing an exception. One case where this might * happen is if we get a MessagingException on each transport.connect(), * e.g., if there is only one server and we get a connect exception. * Return FALSE to keep run() from deleting the message. */ return false; }
From source file:org.openadaptor.auxil.connector.mail.MailConnection.java
/** * @param protocol either pop3/imap (default = pop3) *//*w w w . j a v a 2 s .c o m*/ public void setProtocol(String protocol) throws MessagingException { if (PROTOCOL_POP3.equalsIgnoreCase(protocol) || PROTOCOL_IMAP.equalsIgnoreCase(protocol)) this.protocol = protocol; else throw new MessagingException("Unknown protocol [" + protocol + "]. " + "Use either " + PROTOCOL_POP3 + " or " + PROTOCOL_IMAP); }
From source file:org.openadaptor.auxil.connector.mail.MailConnection.java
/** * Opens the named folder in READ/WRITE mode * * @throws MessagingException if there is a comms error or if the folder could not * be found or we failed to create it// w w w . j a va 2 s.c o m */ public Folder openFolder(String fldr, boolean create) throws MessagingException { if (store == null || !store.isConnected()) connect(); Folder f = store.getFolder(fldr); log.debug("Folder [" + fldr + "] exists? " + f.exists()); // Note that a Folder object is returned even if the named folder does not // physically exist on the Store so we have to test for it explicitly. if (!f.exists()) { // we've not been asked to create the folder so this is an error if (!create) throw new MessagingException("Error opening folder [" + fldr + "]: Folder not found"); // try to create the folder if (!f.create(Folder.HOLDS_MESSAGES)) throw new MessagingException("Failed to create folder [" + fldr + "]"); log.info("Created folder [" + fldr + "]"); } f.open(Folder.READ_WRITE); log.debug("Folder [" + fldr + "] opened"); return f; }
From source file:org.openhealthtools.openatna.net.MailConnection.java
public void sendMessage(Message message) throws MessagingException { if (transport != null && smtp != null) { transport.connect(smtp.getValue("HOSTNAME"), smtp.getValue("USERNAME"), smtp.getValue("PASSWORD")); transport.sendMessage(message, message.getAllRecipients()); transport.close();//from ww w.j ava2 s . co m } else { log.error("Transport and smtp must be set before sending messages."); throw new MessagingException("Attempt to send to invalid smtp connection."); } }
From source file:org.openhealthtools.openatna.net.MailConnection.java
public Message[] retrieveAllMessages() throws MessagingException { Message messages[] = null;/*from www. ja v a 2 s . com*/ if (store != null && pop3 != null) { if (inbox == null) { store.connect(pop3.getValue("HOSTNAME"), pop3.getValue("USERNAME"), pop3.getValue("PASSWORD")); inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); } messages = inbox.getMessages(); } else { log.error("Store and pop3 must be set before retrieving messages."); throw new MessagingException("Attempt to retrieve from invalid pop3 connection."); } return messages; }
From source file:org.openhealthtools.openatna.net.MailConnection.java
public MimeBodyPart decryptMessage(Message message) throws MessagingException { try {/* w w w .j a v a 2 s .c o m*/ /* Add BC */ Security.addProvider(new BouncyCastleProvider()); // Open the key store KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream(getSenderKeystoreFile()), getSenderKeystorePassword().toCharArray()); // find the certificate for the private key and generate a // suitable recipient identifier. X509Certificate cert = (X509Certificate) ks.getCertificate(getSenderKeyAlias()); RecipientId recId = new RecipientId(); recId.setSerialNumber(cert.getSerialNumber()); recId.setIssuer(cert.getIssuerX500Principal().getEncoded()); SMIMEEnveloped m = new SMIMEEnveloped((MimeMessage) message); RecipientInformationStore recipients = m.getRecipientInfos(); // TODO figure out why this doesn't work... //RecipientInformation recipient = recipients.get(recId); RecipientInformation recipient = (RecipientInformation) recipients.getRecipients().iterator().next(); Key key = ks.getKey(getSenderKeyAlias(), getSenderKeystorePassword().toCharArray()); byte[] byteContent = recipient.getContent(key, "BC"); MimeBodyPart res = SMIMEUtil.toMimeBodyPart(byteContent); return res; } catch (Exception e) { log.error("Problem decrypting message: ", e); throw new MessagingException(e.getMessage()); } }