List of usage examples for javax.mail MessagingException MessagingException
public MessagingException(String s, Exception e)
From source file:com.enioka.jqm.tools.Helpers.java
/** * Send a mail message using a JNDI resource.<br> * As JNDI resource providers are inside the EXT class loader, this uses reflection. This method is basically a bonus on top of the * MailSessionFactory offered to payloads, making it accessible also to the engine. * //from w w w . j ava 2 s.com * @param to * @param subject * @param body * @param mailSessionJndiAlias * @throws MessagingException */ @SuppressWarnings({ "unchecked", "rawtypes" }) static void sendMessage(String to, String subject, String body, String mailSessionJndiAlias) throws MessagingException { jqmlogger.debug("sending mail to " + to + " - subject is " + subject); ClassLoader extLoader = getExtClassLoader(); ClassLoader old = Thread.currentThread().getContextClassLoader(); Object mailSession = null; try { mailSession = InitialContext.doLookup(mailSessionJndiAlias); } catch (NamingException e) { throw new MessagingException("could not find mail session description", e); } try { Thread.currentThread().setContextClassLoader(extLoader); Class transportZ = extLoader.loadClass("javax.mail.Transport"); Class sessionZ = extLoader.loadClass("javax.mail.Session"); Class mimeMessageZ = extLoader.loadClass("javax.mail.internet.MimeMessage"); Class messageZ = extLoader.loadClass("javax.mail.Message"); Class recipientTypeZ = extLoader.loadClass("javax.mail.Message$RecipientType"); Object msg = mimeMessageZ.getConstructor(sessionZ).newInstance(mailSession); mimeMessageZ.getMethod("setRecipients", recipientTypeZ, String.class).invoke(msg, recipientTypeZ.getField("TO").get(null), to); mimeMessageZ.getMethod("setSubject", String.class).invoke(msg, subject); mimeMessageZ.getMethod("setText", String.class).invoke(msg, body); transportZ.getMethod("send", messageZ).invoke(null, msg); jqmlogger.trace("Mail was sent"); } catch (Exception e) { throw new MessagingException("an exception occurred during mail sending", e); } finally { Thread.currentThread().setContextClassLoader(old); } }
From source file:mitm.application.djigzo.james.mailets.PDFEncrypt.java
private String createReplyURL(String baseURL, String subject, Collection<MailAddress> recipients, String sender, String replyTo, String serverSecret) throws MessagingException { String replyURL = null;// ww w .ja va 2 s. c o m if (EmailAddressUtils.INVALID_EMAIL.equals(replyTo) || StringUtils.isEmpty(replyTo)) { /* * This happens if the sender of the email is an invalid sender. This will normally only happen if * the global settings allow PDF reply. */ getLogger().warn("Reply-To of the message is an invalid email address. " + "It's not possible to reply to the PDF."); } else if (baseURL != null && serverSecret != null) { /* * The from of the reply (is equal to the recipient of the encrypted PDF) */ String recipient = null; if (recipients.size() == 1) { String notYetValidatedRecipient = recipients.iterator().next().toString(); recipient = EmailAddressUtils.canonicalizeAndValidate(notYetValidatedRecipient, true); if (recipient == null) { getLogger().warn("{} is not a valid recipient.", notYetValidatedRecipient); } } else { getLogger().warn("The mail has multiple recipients. It's not possible to reply to the PDF."); } if (recipient != null && !isReplyAllowed(recipient)) { getLogger().debug("Recipient {} does not allow reply to PDF.", recipient); recipient = null; } if (sender != null && recipient != null) { /* * Make sure the subject is not too long */ subject = StringUtils.abbreviate(StringUtils.trimToEmpty(subject), maxSubjectLength); URLBuilder uRLBuilder = SystemServices.getURLBuilder(); PDFReplyURLBuilder replyBuilder = new PDFReplyURLBuilder(uRLBuilder); replyBuilder.setBaseURL(baseURL); replyBuilder.setUser(sender); replyBuilder.setRecipient(replyTo); /* * The from of the reply message is equal to the original recipient of the PDF (i.e, if the * recipient clicks reply, the sender, aka from, of the reply is set to the recipient of the pdf). */ replyBuilder.setFrom(recipient); replyBuilder.setSubject(subject); replyBuilder.setKey(serverSecret); try { replyURL = replyBuilder.buildURL(); } catch (URLBuilderException e) { throw new MessagingException("Building reply URL failed.", e); } } } return replyURL; }
From source file:mitm.application.djigzo.james.mailets.PDFEncrypt.java
private MimeMessage createMessage(Mail mail, Collection<MailAddress> recipients, PasswordContainer passwordContainer) throws MessagingException, MissingRecipientsException, TemplateException, IOException { Check.notNull(passwordContainer, "passwordContainer"); SimpleHash root = new SimpleHash(); root.put(PASSWORD_CONTAINER_TEMPLATE_PARAM, passwordContainer); /*/*from w w w . j a v a 2 s . c o m*/ * Note: although passwordID can be retrieved from passwordContainer we keep passwordID to make sure * that existing templates that use passwordID are still working */ root.put(PASSWORD_ID_TEMPLATE_PARAM, passwordContainer.getPasswordID()); /* * We should put the real recipient(s) in the Freemarker root. bug https://jira.djigzo.com/browse/GATEWAY-38. */ root.put(RECIPIENTS_TEMPLATE_PARAM, recipients); /* * Get the Reply-To of the message and validate. * * Note: the Reply-To is not canonicalized because that can result in invalid email addresses. For example * "email with space"@example.com is only valid with the quotes. */ String replyTo = EmailAddressUtils.validate(EmailAddressUtils.getEmailAddress( EmailAddressUtils.getAddress(EmailAddressUtils.getReplyToQuietly(mail.getMessage())))); /* * The ReplySettings will be placed in the context since they are needed in #getTemplateFromUser to * get the reply URL */ ReplySettings replySettings = new ReplySettings(mail.getMessage().getSubject(), recipients, replyTo); getActivationContext().set(REPLY_SETTINGS_ACTIVATION_CONTEXT_KEY, replySettings); /* * Create a message from a template. * * Note: Calling createMessage will result in a call to #getTemplateFromUser */ MimeMessage containerMessage = createMessage(mail, root); /* * The call to createMessage should result in the reply URL to be set (if reply is allowed and all * required settings are set) */ String replyURL = replySettings.getReplyURL(); /* * Copy all non content headers from source to notificationMessage. */ HeaderMatcher nonContentMatcher = new NotHeaderNameMatcher(new ContentHeaderNameMatcher()); HeaderUtils.copyHeaders(mail.getMessage(), containerMessage, nonContentMatcher); /* * Create PDF from the source message */ ByteArrayOutputStream pdfStream = new ByteArrayOutputStream(); MessagePDFBuilder pdfBuilder = new MessagePDFBuilder(); pdfBuilder.setFontProvider(fontProvider); if (viewerPreferences != null) { pdfBuilder.setViewerPreference(viewerPreferences); } try { pdfBuilder.buildPDF(mail.getMessage(), replyURL, pdfStream); } catch (DocumentException e) { throw new MessagingException("Error building PDF.", e); } catch (IOException e) { throw new MessagingException("Error building PDF.", e); } byte[] unencryptedPDF = pdfStream.toByteArray(); byte[] encryptedPdf; try { String userPassword = passwordContainer.getPassword(); String ownerPassword = getOwnerPassword(userPassword); encryptedPdf = encryptPDF(unencryptedPDF, userPassword, ownerPassword); } catch (IOException e) { throw new MessagingException("Error encrypting PDF.", e); } catch (DocumentException e) { throw new MessagingException("Error encrypting PDF.", e); } catch (EncryptorException e) { throw new MessagingException("Unable to retrieve password.", e); } /* * Now find and replace the pdf inside the notificationMessage with the encrypted pdf */ addEncryptedPDF(containerMessage, encryptedPdf); containerMessage.saveChanges(); String messageID = null; if (retainMessageID) { messageID = StringUtils.trimToNull(mail.getMessage().getMessageID()); } if (messageID == null) { messageID = MessageIDCreator.getInstance().createUniqueMessageID(); } containerMessage = new MimeMessageWithID(containerMessage, messageID); return containerMessage; }
From source file:mitm.application.djigzo.james.mailets.PDFEncrypt.java
private void sendNotificationSinglePasswordMode(Mail mail) throws MessagingException, MissingRecipientsException, TemplateException, IOException { PasswordContainer passwordContainer; try {// ww w . j av a 2 s . co m passwordContainer = getPasswordContainer(mail); } catch (EncryptorException e) { throw new MessagingException("Unable to retrieve password.", e); } sendNotification(mail, getRecipients(mail), passwordContainer); }
From source file:org.alfresco.repo.imap.IncomingImapMessage.java
/** * Writes the content of incoming message into Alfresco repository. * //from w w w. ja v a 2 s .c om * @throws MessagingException */ private void writeContent() throws MessagingException { ContentWriter writer = serviceRegistry.getContentService().getWriter(messageFileInfo.getNodeRef(), ContentModel.PROP_CONTENT, true); writer.setMimetype(MimetypeMap.MIMETYPE_RFC822); try { OutputStream outputStream = writer.getContentOutputStream(); wrappedMessage.writeTo(outputStream); outputStream.close(); wrappedMessage = null; // it is not used any more and it is available to GC (to avoid memory leak with byte[] MimeMessage.content field) this.contentReader = serviceRegistry.getContentService().getReader(messageFileInfo.getNodeRef(), ContentModel.PROP_CONTENT); } catch (ContentIOException e) { throw new MessagingException(e.getMessage(), e); } catch (IOException e) { throw new MessagingException(e.getMessage(), e); } }
From source file:org.alfresco.repo.imap.IncomingImapMessage.java
@Override protected InputStream getContentStream() throws MessagingException { try {//from w w w . ja v a 2 s.c o m if (this.contentStream == null) { this.contentStream = this.contentReader.getContentInputStream(); } return this.contentStream; } catch (Exception e) { throw new MessagingException(e.getMessage(), e); } }
From source file:org.apache.james.core.MimeMessageInputStreamSource.java
/** * Construct a new MimeMessageInputStreamSource from an * <code>InputStream</code> that contains the bytes of a MimeMessage. * * @param key the prefix for the name of the temp file * @param in the stream containing the MimeMessage * @throws MessagingException if an error occurs while trying to store the stream *//*from w w w .jav a 2 s . c om*/ public MimeMessageInputStreamSource(String key, InputStream in) throws MessagingException { super(); // We want to immediately read this into a temporary file // Create a temp file and channel the input stream into it try { out = new DeferredFileOutputStream(THRESHOLD, key, ".m64", TMPDIR); IOUtils.copy(in, out); sourceId = key; } catch (IOException ioe) { File file = out.getFile(); if (file != null) { FileUtils.deleteQuietly(file); } throw new MessagingException("Unable to retrieve the data: " + ioe.getMessage(), ioe); } finally { try { if (out != null) { out.close(); } } catch (IOException ioe) { // Ignored - logging unavailable to log this non-fatal error. } try { if (in != null) { in.close(); } } catch (IOException ioe) { // Ignored - logging unavailable to log this non-fatal error. } } }
From source file:org.apache.james.core.MimeMessageUtil.java
/** * Write the message headers to the given outputstream * // w ww . java 2 s .c o m * @param headers * the Enumeration which holds the headers * @param headerOs * the OutputStream to which the headers get written * @throws MessagingException */ public static void writeHeadersTo(Enumeration<String> headers, OutputStream headerOs) throws MessagingException { try { IOUtils.copy(new InternetHeadersInputStream(headers), headerOs); } catch (IOException e) { throw new MessagingException("Unable to write headers to stream", e); } }
From source file:org.apache.james.core.MimeMessageUtil.java
/** * Calculate the size of the give mimeMessage * /* w ww .j ava2s.co m*/ * @param message * the MimeMessage * @return size the calculated size * @throws MessagingException * if a problem occours while calculate the message size */ public static long calculateMessageSize(MimeMessage message) throws MessagingException { long size; // SK: Should probably eventually store this as a locally // maintained value (so we don't have to load and reparse // messages each time). size = message.getSize(); if (size != -1) { Enumeration<?> e = message.getAllHeaderLines(); if (e.hasMoreElements()) { size += 2; } while (e.hasMoreElements()) { // add 2 bytes for the CRLF size += ((String) e.nextElement()).length() + 2; } } if (size == -1) { SizeCalculatorOutputStream out = new SizeCalculatorOutputStream(); try { message.writeTo(out); } catch (IOException e) { // should never happen as SizeCalculator does not actually throw // IOExceptions. throw new MessagingException("IOException wrapped by getMessageSize", e); } size = out.getSize(); } return size; }
From source file:org.apache.james.core.MimeMessageWrapper.java
public MimeMessageWrapper(MimeMessage original) throws MessagingException { this(Session.getDefaultInstance(System.getProperties())); flags = original.getFlags();// www . ja va 2 s.c o m if (source == null) { InputStream in; boolean useMemoryCopy = false; String memoryCopy = System.getProperty(USE_MEMORY_COPY); if (memoryCopy != null) { useMemoryCopy = Boolean.valueOf(memoryCopy); } try { if (useMemoryCopy) { ByteArrayOutputStream bos; int size = original.getSize(); if (size > 0) { bos = new ByteArrayOutputStream(size); } else { bos = new ByteArrayOutputStream(); } original.writeTo(bos); bos.close(); in = new SharedByteArrayInputStream(bos.toByteArray()); parse(in); in.close(); saved = true; } else { MimeMessageInputStreamSource src = new MimeMessageInputStreamSource( "MailCopy-" + UUID.randomUUID().toString()); OutputStream out = src.getWritableOutputStream(); original.writeTo(out); out.close(); source = src; } } catch (IOException ex) { // should never happen, but just in case... throw new MessagingException("IOException while copying message", ex); } } }