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) 

Source Link

Document

Constructs a MessagingException with the specified detail message.

Usage

From source file:MailHandlerDemo.java

/**
 * Runs the demo./*from  ww w  . j  a  v  a  2 s .  co  m*/
 *
 * @param args the command line arguments
 * @throws IOException if there is a problem.
 */
public static void main(String[] args) throws IOException {
    List<String> l = Arrays.asList(args);
    if (l.contains("/?") || l.contains("-?") || l.contains("-help")) {
        LOGGER.info("Usage: java MailHandlerDemo " + "[[-all] | [-body] | [-custom] | [-debug] | [-low] "
                + "| [-simple] | [-pushlevel] | [-pushfilter] " + "| [-pushnormal] | [-pushonly]] " + "\n\n"
                + "-all\t\t: Execute all demos.\n" + "-body\t\t: An email with all records and only a body.\n"
                + "-custom\t\t: An email with attachments and dynamic names.\n"
                + "-debug\t\t: Output basic debug information about the JVM " + "and log configuration.\n"
                + "-low\t\t: Generates multiple emails due to low capacity." + "\n"
                + "-simple\t\t: An email with all records with body and " + "an attachment.\n"
                + "-pushlevel\t: Generates high priority emails when the"
                + " push level is triggered and normal priority when " + "flushed.\n"
                + "-pushFilter\t: Generates high priority emails when the "
                + "push level and the push filter is triggered and normal " + "priority emails when flushed.\n"
                + "-pushnormal\t: Generates multiple emails when the "
                + "MemoryHandler push level is triggered.  All generated "
                + "email are sent as normal priority.\n" + "-pushonly\t: Generates multiple emails when the "
                + "MemoryHandler push level is triggered.  Generates high "
                + "priority emails when the push level is triggered and " + "normal priority when flushed.\n");
    } else {
        final boolean debug = init(l); //may create log messages.
        try {
            LOGGER.log(Level.FINEST, "This is the finest part of the demo.",
                    new MessagingException("Fake JavaMail issue."));
            LOGGER.log(Level.FINER, "This is the finer part of the demo.",
                    new NullPointerException("Fake bug."));
            LOGGER.log(Level.FINE, "This is the fine part of the demo.");
            LOGGER.log(Level.CONFIG, "Logging config file is {0}.", getConfigLocation());
            LOGGER.log(Level.INFO, "Your temp directory is {0}, " + "please wait...", getTempDir());

            try { //Waste some time for the custom formatter.
                Thread.sleep(3L * 1000L);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }

            LOGGER.log(Level.WARNING, "This is a warning.",
                    new FileNotFoundException("Fake file chooser issue."));
            LOGGER.log(Level.SEVERE, "The end of the demo.", new IOException("Fake access denied issue."));
        } finally {
            closeHandlers();
        }

        //Force parse errors.  This does have side effects.
        if (debug && getConfigLocation() != null) {
            LogManager.getLogManager().readConfiguration();
        }
    }
}

From source file:dk.dma.msinm.common.mail.AttachmentMailPart.java

/**
 * Instantiates an attachment mail part from a file
 * @param file the attachment file//from w ww. jav  a  2s  .  c  o m
 * @param name the name of the attachment.
 */
public static AttachmentMailPart fromFile(String file, String name) throws MessagingException {
    // Check that the file is valid
    Path path = Paths.get(file);
    if (!Files.isRegularFile(path)) {
        throw new MessagingException("Invalid file attachment: " + file);
    }

    // If name is not specified, compute it from the file
    if (StringUtils.isBlank(name)) {
        name = path.getFileName().toString();
    }

    // Instantiate a mail attachment
    AttachmentMailPart a = new AttachmentMailPart(name);
    a.file = file;
    return a;
}

From source file:com.canoo.webtest.plugins.emailtest.EmailStoreMessageId.java

/**
 * Calculate the message id//  w  ww .j  a  v  a  2s  .  c  o m
 *
 * @param folder
 * @return The extracted count value
 */
protected String processContent(final Folder folder) throws MessagingException {
    final Message[] messages = retrieveMatchingMessages(folder);
    if (StringUtils.isEmpty(fMessageIndex)) {
        LOG.info("Multiple matching messages found, using the first.");
    }
    if (messages.length == 0) {
        throw new MessagingException("No messages matching criteria.");
    }
    final int messageIndex = ConversionUtil.convertToInt(getMessageIndex(), 0);
    if (messageIndex >= messages.length) {
        throw new MessagingException(
                "Invalid messageIndex '" + getMessageIndex() + "', valid range is 0.." + (messages.length - 1));
    }
    return String.valueOf(messages[messageIndex].getMessageNumber());
}

From source file:org.openlmis.notification.service.NotificationService.java

/**
 * Send an email notification.//from  www  .jav  a2 s .co m
 *
 * @param from email address of the sender
 * @param to email address of the receiver
 * @param subject subject of the email
 * @param content content of the email
 * @throws MessagingException a generic messaging exception
 */
public void sendNotification(String from, String to, String subject, String content) throws MessagingException {
    if (content == null) {
        throw new MessagingException("Content must not be null");
    }
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, false);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content);

    mailSender.send(message);
}

From source file:org.toobsframework.email.SmtpMailSender.java

public void sendEmail(EmailBean email) throws MailException, MessagingException {
    JavaMailSender javaMailSender = (JavaMailSender) javaMailSenders.get(email.getMailSenderKey());
    if (javaMailSender == null) {
        throw new MessagingException(email.getMailSenderKey() + " is an invalid mailSenderKey");
    }// w  w  w . jav  a 2s.c  o m
    if (this.getMailProperties() != null) {
        ((JavaMailSenderImpl) javaMailSender).setJavaMailProperties(this.getMailProperties());
    }
    try {
        String[] recipients = this.processRecipients(email.getRecipients());
        String[] bccs = new String[email.getBccs().size()];
        for (int i = 0; i < recipients.length; i++) {
            MimeMessage message = null;
            MimeMessageHelper helper = null;
            String thisRecipient = recipients[i];
            switch (email.getType()) {
            case EmailBean.MESSAGE_TYPE_TEXT:
                message = javaMailSender.createMimeMessage();
                helper = new MimeMessageHelper(message, false, "us-ascii");
                helper.setSubject(email.getEmailSubject());
                helper.setFrom(email.getEmailSender());

                helper.setTo(thisRecipient);
                helper.setBcc((String[]) email.getBccs().toArray(bccs));
                helper.setText(email.getMessageText(), false);
                log.info("Sending message " + message.toString());
                javaMailSender.send(message);
                break;
            case EmailBean.MESSAGE_TYPE_HTML:
                message = javaMailSender.createMimeMessage();
                helper = new MimeMessageHelper(message, true, "us-ascii");
                helper.setSubject(email.getEmailSubject());
                helper.setFrom(email.getEmailSender());

                helper.setTo(thisRecipient);
                helper.setBcc((String[]) email.getBccs().toArray(bccs));
                helper.setText(email.getMessageText(), email.getMessageHtml());
                log.info("Sending message " + message.toString());
                javaMailSender.send(message);
                break;
            }
        }
    } catch (Exception e) {
        log.error("Mail exception " + e.getMessage(), e);
        throw new MessagingException(e.getMessage());
    }
}

From source file:com.canoo.webtest.plugins.emailtest.EmailMessageStructureFilter.java

protected void filterContent(final Message message) throws MessagingException {
    if (!StringUtils.isEmpty(getHeaders())) {
        prepareHeaders();/*from  w  ww. j  av a  2  s .  c o m*/
    }
    try {
        final Object content = message.getContent();
        if (content instanceof Multipart) {
            filterMultiPartMessage(content, message);
            return;
        }
        filterSimpleMessage((String) content, message);
    } catch (IOException e) {
        LOG.error("Error processing email message: ", e);
        throw new MessagingException("Error processing email message: " + e.getMessage());
    }
}

From source file:EmailBean.java

public void sendMessage() throws Exception {

    Properties properties = System.getProperties();

    //populate the 'Properties' object with the mail
    //server address, so that the default 'Session'
    //instance can use it.
    properties.put("mail.smtp.host", smtpHost);

    Session session = Session.getDefaultInstance(properties);

    Message mailMsg = new MimeMessage(session);//a new email message

    InternetAddress[] addresses = null;//from w  w w  . j av  a 2  s.  c  o m

    try {

        if (to != null) {

            //throws 'AddressException' if the 'to' email address
            //violates RFC822 syntax
            addresses = InternetAddress.parse(to, false);

            mailMsg.setRecipients(Message.RecipientType.TO, addresses);

        } else {

            throw new MessagingException("The mail message requires a 'To' address.");

        }

        if (from != null) {

            mailMsg.setFrom(new InternetAddress(from));

        } else {

            throw new MessagingException("The mail message requires a valid 'From' address.");

        }

        if (subject != null)
            mailMsg.setSubject(subject);

        if (content != null)
            mailMsg.setText(content);

        //Finally, send the mail message; throws a 'SendFailedException'
        //if any of the message's recipients have an invalid address
        Transport.send(mailMsg);

    } catch (Exception exc) {

        throw exc;

    }

}

From source file:dk.dma.msinm.common.mail.AttachmentMailPart.java

/**
 * Instantiates an attachment mail part from a URL
 * @param urlStr the attachment URL//from ww  w .ja  va 2s .com
 * @param name the name of the attachment.
 */
public static AttachmentMailPart fromUrl(String urlStr, String name) throws MessagingException {
    // Check that the file is valid
    URL url;
    try {
        url = new URL(urlStr);
    } catch (MalformedURLException ex) {
        throw new MessagingException("Invalid url attachment: " + urlStr);
    }

    // If name is not specified, compute it from the file
    if (StringUtils.isBlank(name)) {
        name = url.getPath();
        if (name.contains("/")) {
            name = name.substring(name.lastIndexOf("/") + 1);
        }
        if (StringUtils.isBlank(name)) {
            name = "unknown";
        }
    }

    // Instantiate a mail attachment
    AttachmentMailPart a = new AttachmentMailPart(name);
    a.url = url;
    return a;
}

From source file:com.canoo.webtest.plugins.emailtest.EmailStoreHeader.java

/**
 * Calculate the result./*from  w  w w  . ja v a  2 s.  c o m*/
 *
 * @param message
 * @return The result
 */
protected String performOperation(final Message message) throws MessagingException {
    if (StringUtils.isEmpty(getPartIndex())) {
        return arrayToString(message.getHeader(getHeaderName()));
    }
    final Object content;
    try {
        content = message.getContent();
    } catch (IOException e) {
        LOG.error("Error processing email message: ", e);
        throw new MessagingException("Error processing email message: " + e.getMessage());
    }
    if (content instanceof Multipart) {
        final Multipart mp = (Multipart) content;
        final int part = ConversionUtil.convertToInt(getPartIndex(), 0);
        if (part >= mp.getCount()) {
            throw new StepFailedException("PartIndex too large.", this);
        }
        return arrayToString(mp.getBodyPart(part).getHeader(getHeaderName()));
    }
    throw new StepFailedException("PartIndex supplied for a non-MultiPart message.", this);
}

From source file:com.canoo.webtest.plugins.emailtest.EmailMessageContentFilter.java

protected void filterContent(final Message message) throws MessagingException {
    if (StringUtils.isEmpty(getPartIndex())) {
        try {/*w ww. j av a  2  s. c o m*/
            defineAsCurrentResponse(IOUtils.toString(message.getInputStream()), message.getContentType());
            return;
        } catch (IOException e) {
            throw new MessagingException("Error extracting message: " + e.getMessage());
        }
    }
    final int partIndex = ConversionUtil.convertToInt(getPartIndex(), 0);
    try {
        final Object content = message.getContent();
        if (content instanceof Multipart) {
            extractMultiPartMessage((Multipart) content, partIndex);
            return;
        }
        extractSimpleMessage((String) content, partIndex);
    } catch (IOException e) {
        LOG.error("Error processing email message: ", e);
        throw new MessagingException("Error processing email message: " + e.getMessage());
    }
}