Example usage for javax.mail MessagingException MessagingException

List of usage examples for javax.mail MessagingException MessagingException

Introduction

In this page you can find the example usage for javax.mail MessagingException MessagingException.

Prototype

public MessagingException(String s, Exception e) 

Source Link

Document

Constructs a MessagingException with the specified Exception and detail message.

Usage

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();/*from ww  w. jav  a 2s  .c o m*/
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);
}

From source file:com.haulmont.cuba.core.app.EmailSender.java

protected void assignFromAddress(SendingMessage sendingMessage, MimeMessage msg) throws MessagingException {
    InternetAddress[] internetAddresses = InternetAddress.parse(sendingMessage.getFrom());
    for (InternetAddress internetAddress : internetAddresses) {
        if (StringUtils.isNotEmpty(internetAddress.getPersonal())) {
            try {
                internetAddress.setPersonal(internetAddress.getPersonal(), StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                throw new MessagingException("Unsupported encoding type", e);
            }/* ww w.  ja  v a2s . c  om*/
        }
    }

    if (internetAddresses.length == 1) {
        msg.setFrom(internetAddresses[0]);
    } else {
        msg.addFrom(internetAddresses);
    }
}

From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java

public MimeMessage transform(MimeMessage message) throws MessagingException {
    MimeBodyPart sentToBodyPart = newSentToBodyPart(message);
    MimeBodyPart originalBodyPart = newOriginalBodyPart(message);

    // create a new multipart content for this message.
    MimeMultipart multipart = new MimeMultipart(EmailUtil.SUBTYPE_MIXED);

    // add the parts to the body.
    multipart.addBodyPart(originalBodyPart);
    multipart.addBodyPart(sentToBodyPart);

    // get the new values for all of the headers.
    InternetAddress newFromAddress = newFromAddress(message);
    InternetAddress[] newToAddresses = newToAddresses(message);
    InternetAddress[] newCcAddresses = newCcAddresses(message);
    InternetAddress[] newBccAddresses = newBccAddresses(message);
    String newSubject = newSubject(message);

    // update the message.
    message.setFrom(newFromAddress);//from w w  w. ja  v  a  2s. c om
    message.setRecipients(Message.RecipientType.TO, newToAddresses);
    message.setRecipients(Message.RecipientType.CC, newCcAddresses);
    message.setRecipients(Message.RecipientType.BCC, newBccAddresses);
    message.setSubject(newSubject);
    message.setContent(multipart);

    // save the message.
    message.saveChanges();

    if (getLogProperty()) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            message.writeTo(out);
            log.info("Email Message Sent:\n{}", out.toString());
        } catch (IOException ioe) {
            throw new MessagingException("Exception thrown while writing message to log.", ioe);
        }
    }
    if (!getSendProperty()) {
        message = null;
    }

    // return the message.
    return message;
}

From source file:mitm.application.djigzo.james.matchers.AbstractEvaluateUser.java

protected boolean hasMatch(Mail mail, User user) throws MessagingException {
    Evaluator evaluator = getEvaluator();

    addFunctions(evaluator);//from w  ww.ja  va2 s .  c o  m

    evaluator.setVariableResolver(getVariableResolver(mail, user));

    try {
        return evaluator.getBooleanResult(expression);
    } catch (EvaluationException e) {
        throw new MessagingException("expression cannot be evaluated.", e);
    }
}

From source file:mitm.application.djigzo.james.matchers.RecipientIsSenderProperty.java

protected String getBlackBerryRelayEmail(final Mail mail, final Collection<MailAddress> mailAddresses)
        throws MessagingException {
    MailAddressMatcher.HasMatchEventHandler hasMatchEventHandler = new MailAddressMatcher.HasMatchEventHandler() {
        @Override//w ww. j ava 2s  . co m
        public boolean hasMatch(final User user) throws MessagingException {
            String blackBerryRelayEmail;

            try {
                blackBerryRelayEmail = user.getUserPreferences().getProperties().getProperty(userProperty,
                        false);
            } catch (HierarchicalPropertiesException e) {
                throw new MessagingException(
                        "Error getting blackBerryRelayEmail from property: " + userProperty, e);
            }

            getActivationContext().set(ACTIVATION_CONTEXT_KEY, blackBerryRelayEmail);

            return true;
        }
    };

    MailAddressMatcher matcher = new MailAddressMatcher(sessionManager, userWorkflow, actionExecutor,
            hasMatchEventHandler, ACTION_RETRIES);

    matcher.getMatchingMailAddresses(mailAddresses);

    return getActivationContext().get(ACTIVATION_CONTEXT_KEY, String.class);
}

From source file:mitm.application.djigzo.james.matchers.VerifyHMACHeader.java

private String calculateHMAC(String value, Mail mail) throws MessagingException, MissingSecretException {
    try {/*from   www . java2  s . c  o  m*/
        Mac mac = securityFactory.createMAC(ALGORITHM);

        byte[] secret = getSecret(mail);

        if (secret == null) {
            throw new MissingSecretException();
        }

        SecretKeySpec keySpec = new SecretKeySpec(secret, "raw");

        mac.init(keySpec);

        mac.update(MiscStringUtils.toAsciiBytes(value));

        return HexUtils.hexEncode(mac.doFinal());
    } catch (NoSuchAlgorithmException e) {
        throw new MessagingException("Error creating HMAC.", e);
    } catch (NoSuchProviderException e) {
        throw new MessagingException("Error creating HMAC.", e);
    } catch (InvalidKeyException e) {
        throw new MessagingException("Error creating HMAC.", e);
    }
}

From source file:immf.Util.java

public static void setFileName(Part part, String filename, String charset, String lang)
        throws MessagingException {

    ContentDisposition disposition;/*from ww  w. j  av a2s.c  o  m*/
    String[] strings = part.getHeader("Content-Disposition");
    if (strings == null || strings.length < 1) {
        disposition = new ContentDisposition(Part.ATTACHMENT);
    } else {
        disposition = new ContentDisposition(strings[0]);
        disposition.getParameterList().remove("filename");
    }

    part.setHeader("Content-Disposition",
            disposition.toString() + encodeParameter("filename", filename, charset, lang));

    ContentType cType;
    strings = part.getHeader("Content-Type");
    if (strings == null || strings.length < 1) {
        cType = new ContentType(part.getDataHandler().getContentType());
    } else {
        cType = new ContentType(strings[0]);
    }

    try {
        // I want to public the MimeUtility#doEncode()!!!
        String mimeString = MimeUtility.encodeWord(filename, charset, "B");
        // cut <CRLF>...
        StringBuffer sb = new StringBuffer();
        int i;
        while ((i = mimeString.indexOf('\r')) != -1) {
            sb.append(mimeString.substring(0, i));
            mimeString = mimeString.substring(i + 2);
        }
        sb.append(mimeString);

        cType.setParameter("name", new String(sb));
    } catch (UnsupportedEncodingException e) {
        throw new MessagingException("Encoding error", e);
    }
    part.setHeader("Content-Type", cType.toString());
}

From source file:mitm.application.djigzo.james.mailets.CreatePortalInvitation.java

protected void onHandleUserEvent(User user) throws MessagingException {
    try {//  w  w  w. j av a2s.com
        ActivationContext activationContext = getActivationContext().get(ACTIVATION_CONTEXT_KEY,
                ActivationContext.class);

        Check.notNull(activationContext, "activationContext");

        String serverSecret = user.getUserPreferences().getProperties().getServerSecret();

        if (StringUtils.isNotEmpty(serverSecret)) {
            PortalInvitationValidator validator = new PortalInvitationValidator();

            long timestamp = System.currentTimeMillis();

            validator.setEmail(user.getEmail());
            validator.setTimestamp(timestamp);

            activationContext.getInvitations().put(user.getEmail(),
                    new PortalInvitationDetails(timestamp, validator.calulateMAC(serverSecret)));
        } else {
            /*
             * Should not happen because the server secret should always be set
             */
            logger.warn("Server secret not set for user " + user.getEmail());
        }
    } catch (HierarchicalPropertiesException e) {
        throw new MessagingException("Error handling user " + user.getEmail(), e);
    } catch (ValidatorException e) {
        throw new MessagingException("Error calculating MAC for user " + user.getEmail(), e);
    }
}

From source file:mitm.application.djigzo.james.mailets.GenerateClientSecret.java

protected void onHandleUserEvent(User user) throws MessagingException {
    UserProperties userProperties = user.getUserPreferences().getProperties();

    try {/*  ww  w . j  av  a2  s  .  co m*/
        /*
         * Check if the user does not yet have a client secret. This is required to prevent 
         * a possible race condition. The check if the user has a secret is done with a matcher. 
         * After the check, it can happen that a client secret was already created within a different 
         * thread (hence the race condition).
         */
        if (StringUtils.isEmpty(userProperties.getClientSecret()) || !skipIfClientSecretSet) {
            userProperties.setClientSecret(passwordGenerator.generatePassword(clientSecretLength));

            /*
             * Since we have created a client secret, we need to make the user persistent
             */
            userWorkflow.makePersistent(user);
        }
    } catch (HierarchicalPropertiesException e) {
        throw new MessagingException("Error creating client secret for user " + user.getEmail(), e);
    }
}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments)
        throws MessagingException {
    Transport t = null;//from  w  ww  .  j av a2s.c o m

    try {
        MimeMessage message = new MimeMessage(session);

        t = session.getTransport("smtp");

        message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        if (attachments == null || attachments.size() < 1) {
            message.setText(text);
        } else {
            // create the message part 
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(text);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            try {
                for (InputStream attachment : attachments.keySet()) {
                    messageBodyPart = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream");

                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR 
                    multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val
                }
            } catch (IOException e) {
                throw new MessagingException("cannot add an attachment to mail", e);
            }
            message.setContent(multipart);
        }

        t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

        t.sendMessage(message, message.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }

}