Example usage for javax.mail MessagingException getMessage

List of usage examples for javax.mail MessagingException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.cws.esolutions.core.main.EmailUtility.java

public static final void main(final String[] args) {
    final String methodName = EmailUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {// w w w  .  j  a v a 2s  .  c  o  m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", (Object) args);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(EmailUtility.CNAME, options, true);

        return;
    }

    try {
        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        URL xmlURL = null;
        JAXBContext context = null;
        Unmarshaller marshaller = null;
        CoreConfigurationData configData = null;

        xmlURL = FileUtils.getFile(commandLine.getOptionValue("config")).toURI().toURL();
        context = JAXBContext.newInstance(CoreConfigurationData.class);
        marshaller = context.createUnmarshaller();
        configData = (CoreConfigurationData) marshaller.unmarshal(xmlURL);

        EmailMessage message = new EmailMessage();
        message.setMessageTo(new ArrayList<String>(Arrays.asList(commandLine.getOptionValues("to"))));
        message.setMessageSubject(commandLine.getOptionValue("subject"));
        message.setMessageBody((String) commandLine.getArgList().get(0));
        message.setEmailAddr((StringUtils.isNotEmpty(commandLine.getOptionValue("from")))
                ? new ArrayList<String>(Arrays.asList(commandLine.getOptionValue("from")))
                : new ArrayList<String>(Arrays.asList(configData.getMailConfig().getMailFrom())));

        if (DEBUG) {
            DEBUGGER.debug("EmailMessage: {}", message);
        }

        try {
            EmailUtils.sendEmailMessage(configData.getMailConfig(), message, false);
        } catch (MessagingException mx) {
            System.err.println(
                    "An error occurred while sending the requested message. Exception: " + mx.getMessage());
        }
    } catch (ParseException px) {
        px.printStackTrace();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(EmailUtility.CNAME, options, true);
    } catch (MalformedURLException mx) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(EmailUtility.CNAME, options, true);
    } catch (JAXBException jx) {
        jx.printStackTrace();
        System.err.println("An error occurred while loading the provided configuration file. Cannot continue.");
    }
}

From source file:populate.java

public static void main(String argv[]) {
    String srcURL = null;/*from  www .j  a v a2 s  .  co m*/
    String dstURL = null;
    boolean debug = false;

    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-s")) {
            srcURL = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            dstURL = argv[++optind];
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            force = true;
        } else if (argv[optind].equals("-S")) {
            skipSpecial = true;
        } else if (argv[optind].equals("-c")) {
            clear = true;
        } else if (argv[optind].equals("-P")) {
            dontPreserveFlags = true;
        } else if (argv[optind].equals("-W")) {
            warn = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            printUsage();
            System.exit(1);
        } else {
            break;
        }
    }

    try {

        if (srcURL == null || dstURL == null) {
            printUsage();
            System.exit(1);
        }

        Session session = Session.getInstance(System.getProperties(), null);
        session.setDebug(debug);

        // Get source folder
        URLName srcURLName = new URLName(srcURL);
        Folder srcFolder;
        // Check if the source URL has a folder specified. If
        // not, we use the default folder
        if (srcURLName.getFile() == null) {
            Store s = session.getStore(srcURLName);
            s.connect();
            srcFolder = s.getDefaultFolder();
        } else {
            srcFolder = session.getFolder(new URLName(srcURL));
            if (!srcFolder.exists()) {
                System.out.println("source folder does not exist");
                srcFolder.getStore().close();
                System.exit(1);
            }
        }

        // Set up destination folder
        URLName dstURLName = new URLName(dstURL);
        Folder dstFolder;
        // Check if the destination URL has a folder specified. If
        // not, we use the source folder name
        if (dstURLName.getFile() == null) {
            Store s = session.getStore(dstURLName);
            s.connect();
            dstFolder = s.getFolder(srcFolder.getName());
        } else
            dstFolder = session.getFolder(dstURLName);

        if (clear && dstFolder.exists()) {
            if (!dstFolder.delete(true)) {
                System.out.println("couldn't delete " + dstFolder.getFullName());
                return;
            }
        }
        copy(srcFolder, dstFolder);

        // Close the respective stores.
        srcFolder.getStore().close();
        dstFolder.getStore().close();

    } catch (MessagingException mex) {
        System.out.println(mex.getMessage());
        mex.printStackTrace();
    }
}

From source file:populate.java

public static void main(String argv[]) {
    String srcURL = null;/* ww  w  .j  ava 2  s.co m*/
    String dstURL = null;
    boolean debug = false;

    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-s")) {
            srcURL = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            dstURL = argv[++optind];
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            force = true;
        } else if (argv[optind].equals("-S")) {
            skipSpecial = true;
        } else if (argv[optind].equals("-c")) {
            clear = true;
        } else if (argv[optind].equals("-P")) {
            dontPreserveFlags = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            printUsage();
            System.exit(1);
        } else {
            break;
        }
    }

    try {

        if (srcURL == null || dstURL == null) {
            printUsage();
            System.exit(1);
        }

        Session session = Session.getInstance(System.getProperties(), null);
        session.setDebug(debug);

        // Get source folder
        URLName srcURLName = new URLName(srcURL);
        Folder srcFolder;
        // Check if the source URL has a folder specified. If
        // not, we use the default folder
        if (srcURLName.getFile() == null) {
            Store s = session.getStore(srcURLName);
            s.connect();
            srcFolder = s.getDefaultFolder();
        } else {
            srcFolder = session.getFolder(new URLName(srcURL));
            if (!srcFolder.exists()) {
                System.out.println("source folder does not exist");
                srcFolder.getStore().close();
                System.exit(1);
            }
        }

        // Set up destination folder
        URLName dstURLName = new URLName(dstURL);
        Folder dstFolder;
        // Check if the destination URL has a folder specified. If
        // not, we use the source folder name
        if (dstURLName.getFile() == null) {
            Store s = session.getStore(dstURLName);
            s.connect();
            dstFolder = s.getFolder(srcFolder.getName());
        } else
            dstFolder = session.getFolder(dstURLName);

        if (clear && dstFolder.exists()) {
            if (!dstFolder.delete(true)) {
                System.out.println("couldn't delete " + dstFolder.getFullName());
                return;
            }
        }
        copy(srcFolder, dstFolder);

        // Close the respective stores.
        srcFolder.getStore().close();
        dstFolder.getStore().close();

    } catch (MessagingException mex) {
        System.out.println(mex.getMessage());
        mex.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String argv[]) {
    int msgnum = -1;
    int optind;/*ww  w.  ja  v  a  2s.com*/
    InputStream msgStream = System.in;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-p")) {
            port = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("-s")) {
            showStructure = true;
        } else if (argv[optind].equals("-S")) {
            saveAttachments = true;
        } else if (argv[optind].equals("-m")) {
            showMessage = true;
        } else if (argv[optind].equals("-a")) {
            showAlert = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
            System.out.println("\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]");
            System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length)
            msgnum = Integer.parseInt(argv[optind]);

        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        if (showMessage) {
            MimeMessage msg;
            if (mbox != null)
                msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
            else
                msg = new MimeMessage(session, msgStream);
            dumpPart(msg);
            System.exit(0);
        }

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            if (showAlert) {
                store.addStoreListener(new StoreListener() {
                    public void notification(StoreEvent e) {
                        String s;
                        if (e.getMessageType() == StoreEvent.ALERT)
                            s = "ALERT: ";
                        else
                            s = "NOTICE: ";
                        System.out.println(s + e.getMessage());
                    }
                });
            }
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, port, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        if (mbox == null)
            mbox = "INBOX";
        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (msgnum == -1) {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            System.out.println("Getting message number: " + msgnum);
            Message m = null;

            try {
                m = folder.getMessage(msgnum);
                dumpPart(m);
            } catch (IndexOutOfBoundsException iex) {
                System.out.println("Message number out of range");
            }
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:msgshow.java

public static void main(String argv[]) {
    int optind;//from ww  w. ja v a 2s.  c om
    InputStream msgStream = System.in;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-p")) {
            port = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("-s")) {
            showStructure = true;
        } else if (argv[optind].equals("-S")) {
            saveAttachments = true;
        } else if (argv[optind].equals("-m")) {
            showMessage = true;
        } else if (argv[optind].equals("-a")) {
            showAlert = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
            System.out.println("\t[-P password] [-f mailbox] [msgnum ...] [-v] [-D] [-s] [-S] [-a]");
            System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        if (showMessage) {
            MimeMessage msg;
            if (mbox != null)
                msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
            else
                msg = new MimeMessage(session, msgStream);
            dumpPart(msg);
            System.exit(0);
        }

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            if (showAlert) {
                store.addStoreListener(new StoreListener() {
                    public void notification(StoreEvent e) {
                        String s;
                        if (e.getMessageType() == StoreEvent.ALERT)
                            s = "ALERT: ";
                        else
                            s = "NOTICE: ";
                        System.out.println(s + e.getMessage());
                    }
                });
            }
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, port, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        if (mbox == null)
            mbox = "INBOX";
        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (optind >= argv.length) {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            while (optind < argv.length) {
                int msgnum = Integer.parseInt(argv[optind++]);
                System.out.println("Getting message number: " + msgnum);
                Message m = null;

                try {
                    m = folder.getMessage(msgnum);
                    dumpPart(m);
                } catch (IndexOutOfBoundsException iex) {
                    System.out.println("Message number out of range");
                }
            }
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:org.owasp.dependencycheck.analyzer.PythonDistributionAnalyzer.java

/**
 * Reads the manifest entries from the provided file.
 *
 * @param manifest the manifest/*  w  ww .  j av a 2 s .c  om*/
 * @return the manifest entries
 */
private static InternetHeaders getManifestProperties(File manifest) {
    final InternetHeaders result = new InternetHeaders();
    if (null == manifest) {
        LOGGER.debug("Manifest file not found.");
    } else {
        try {
            result.load(new AutoCloseInputStream(new BufferedInputStream(new FileInputStream(manifest))));
        } catch (MessagingException e) {
            LOGGER.warn(e.getMessage(), e);
        } catch (FileNotFoundException e) {
            LOGGER.warn(e.getMessage(), e);
        }
    }
    return result;
}

From source file:org.apache.jmeter.assertions.SMIMEAssertion.java

public static AssertionResult getResult(SMIMEAssertionTestElement testElement, SampleResult response,
        String name) {//  w w  w  . j  a va 2 s.c o m
    checkForBouncycastle();
    AssertionResult res = new AssertionResult(name);
    try {
        MimeMessage msg = null;
        final int msgPos = testElement.getSpecificMessagePositionAsInt();
        if (msgPos < 0) { // means counting from end
            SampleResult[] subResults = response.getSubResults();
            final int pos = subResults.length + msgPos;
            if (log.isDebugEnabled()) {
                log.debug("Getting message number: " + pos + " of " + subResults.length);
            }
            msg = getMessageFromResponse(response, pos);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Getting message number: " + msgPos);
            }
            msg = getMessageFromResponse(response, msgPos);
        }

        SMIMESignedParser s = null;
        if (log.isDebugEnabled()) {
            log.debug("Content-type: " + msg.getContentType());
        }
        if (msg.isMimeType("multipart/signed")) { // $NON-NLS-1$
            MimeMultipart multipart = (MimeMultipart) msg.getContent();
            s = new SMIMESignedParser(new BcDigestCalculatorProvider(), multipart);
        } else if (msg.isMimeType("application/pkcs7-mime") // $NON-NLS-1$
                || msg.isMimeType("application/x-pkcs7-mime")) { // $NON-NLS-1$
            s = new SMIMESignedParser(new BcDigestCalculatorProvider(), msg);
        }

        if (null != s) {
            log.debug("Found signature");

            if (testElement.isNotSigned()) {
                res.setFailure(true);
                res.setFailureMessage("Mime message is signed");
            } else if (testElement.isVerifySignature() || !testElement.isSignerNoCheck()) {
                res = verifySignature(testElement, s, name);
            }

        } else {
            log.debug("Did not find signature");
            if (!testElement.isNotSigned()) {
                res.setFailure(true);
                res.setFailureMessage("Mime message is not signed");
            }
        }

    } catch (MessagingException e) {
        String msg = "Cannot parse mime msg: " + e.getMessage();
        log.warn(msg, e);
        res.setFailure(true);
        res.setFailureMessage(msg);
    } catch (CMSException e) {
        res.setFailure(true);
        res.setFailureMessage("Error reading the signature: " + e.getMessage());
    } catch (SMIMEException e) {
        res.setFailure(true);
        res.setFailureMessage("Cannot extract signed body part from signature: " + e.getMessage());
    } catch (IOException e) { // should never happen
        log.error("Cannot read mime message content: " + e.getMessage(), e);
        res.setError(true);
        res.setFailureMessage(e.getMessage());
    }

    return res;
}

From source file:no.kantega.publishing.modules.mailsender.MailSender.java

/**
 * Sends a mail message. The content must be provided as MimeBodyPart objects.
 *
 * @param from      Sender's email address.
 * @param to        Recipient's email address.
 * @param cc        Email address for CC.
 * @param bcc       Email address for BCC.
 * @param subject   Subject text for the email.
 * @param bodyParts The body parts to insert into the message.
 * @throws SystemException        if an unexpected error occurs.
 * @throws ConfigurationException if a configuration error occurs.
 *//*from w w  w.j  a va2 s  .co  m*/
public static void send(String from, String to, String cc, String bcc, String subject, MimeBodyPart[] bodyParts)
        throws ConfigurationException, SystemException {

    initEventLog();

    try {
        Properties props = new Properties();

        Configuration config = Aksess.getConfiguration();
        String host = config.getString("mail.host");
        if (host == null) {
            throw new ConfigurationException("mail.host");
        }

        // I noen tilfeller nsker vi at all epost skal g til en testadresse
        String catchAllTo = config.getString("mail.catchall.to");
        boolean catchallExists = catchAllTo != null && catchAllTo.contains("@");
        if (catchallExists) {
            StringBuilder prefix = new StringBuilder(" (original recipient: " + to);
            if (cc != null) {
                prefix.append(", cc: ").append(cc);
            }
            if (bcc != null) {
                prefix.append(", bcc: ").append(bcc);
            }
            prefix.append(") ");
            subject = prefix + subject;
            to = catchAllTo;
            cc = null;
            bcc = null;
        }

        props.setProperty("mail.smtp.host", host);

        Session session = Session.getDefaultInstance(props);

        boolean debug = config.getBoolean("mail.debug", false);
        if (debug) {
            session.setDebug(true);
        }

        // Opprett message, sett attributter
        MimeMessage message = new MimeMessage(session);
        InternetAddress fromAddress = new InternetAddress(from);
        InternetAddress toAddress[] = InternetAddress.parse(to);

        message.setFrom(fromAddress);

        if (toAddress.length > 1) {
            message.setRecipients(Message.RecipientType.BCC, toAddress);
        } else {
            message.setRecipients(Message.RecipientType.TO, toAddress);
        }
        if (cc != null) {
            message.addRecipients(Message.RecipientType.CC, cc);
        }
        if (bcc != null) {
            message.addRecipients(Message.RecipientType.BCC, bcc);
        }

        message.setSubject(subject, "ISO-8859-1");
        message.setSentDate(new Date());

        Multipart mp = new MimeMultipart();
        for (MimeBodyPart bodyPart : bodyParts) {
            mp.addBodyPart(bodyPart);
        }
        message.setContent(mp);

        // Send meldingen
        Transport.send(message);

        eventLog.log("System", null, Event.EMAIL_SENT, to + ":" + subject, null);

        // Logg sending
        log.info("Sending email to " + to + " with subject " + subject);
    } catch (MessagingException e) {
        String errormessage = "Subject: " + subject + " | Error: " + e.getMessage();
        eventLog.log("System", null, Event.FAILED_EMAIL_SUBMISSION, errormessage + " | to: " + to, null);
        log.error("Error sending mail", e);
        throw new SystemException("Error sending email to : " + to + " with subject " + subject, e);
    }
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize
 * @param message - The email message/*  w  w w.j  a  va 2s .c  om*/
 * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message
 */
public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message,
        final boolean isWeb) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException";

    Session mailSession = null;

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", mailConfig);
        DEBUGGER.debug("Value: {}", message);
        DEBUGGER.debug("Value: {}", isWeb);
    }

    SMTPAuthenticator smtpAuth = null;

    if (DEBUG) {
        DEBUGGER.debug("MailConfig: {}", mailConfig);
    }

    try {
        if (isWeb) {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT);

            if (DEBUG) {
                DEBUGGER.debug("InitialContext: {}", initContext);
                DEBUGGER.debug("Context: {}", envContext);
            }

            if (envContext != null) {
                mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName());
            }
        } else {
            Properties mailProps = new Properties();

            try {
                mailProps.load(
                        EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile()));
            } catch (NullPointerException npx) {
                try {
                    mailProps.load(new FileInputStream(mailConfig.getPropertyFile()));
                } catch (IOException iox) {
                    throw new MessagingException(iox.getMessage(), iox);
                }
            } catch (IOException iox) {
                throw new MessagingException(iox.getMessage(), iox);
            }

            if (DEBUG) {
                DEBUGGER.debug("Properties: {}", mailProps);
            }

            if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) {
                smtpAuth = new SMTPAuthenticator();
                mailSession = Session.getDefaultInstance(mailProps, smtpAuth);
            } else {
                mailSession = Session.getDefaultInstance(mailProps);
            }
        }

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        MimeMessage mailMessage = new MimeMessage(mailSession);

        // Our emailList parameter should contain the following
        // items (in this order):
        // 0. Recipients
        // 1. From Address
        // 2. Generated-From (if blank, a default value is used)
        // 3. The message subject
        // 4. The message content
        // 5. The message id (optional)
        // We're only checking to ensure that the 'from' and 'to'
        // values aren't null - the rest is really optional.. if
        // the calling application sends a blank email, we aren't
        // handing it here.
        if (message.getMessageTo().size() != 0) {
            for (String to : message.getMessageTo()) {
                if (DEBUG) {
                    DEBUGGER.debug(to);
                }

                mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0)));
            mailMessage.setSubject(message.getMessageSubject());
            mailMessage.setContent(message.getMessageBody(), "text/html");

            if (message.isAlert()) {
                mailMessage.setHeader("Importance", "High");
            }

            Transport mailTransport = mailSession.getTransport("smtp");

            if (DEBUG) {
                DEBUGGER.debug("Transport: {}", mailTransport);
            }

            mailTransport.connect();

            if (mailTransport.isConnected()) {
                Transport.send(mailMessage);
            }
        }
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } catch (NamingException nx) {
        throw new MessagingException(nx.getMessage(), nx);
    }
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * /*from  w  ww. ja  v a  2 s . c o  m*/
 * 
 * @param msg
 * @return
 */
public static int getMessagePriority(Message msg) {

    int prio = CubusConstants.PRIORITY_NONE;

    try {
        String header[] = msg.getHeader(CubusConstants.FETCH_ITEM_PRIORITY);
        if (header != null && header.length > 0 && header[0].length() > 0) {
            String first = header[0].substring(0, 1);
            if (StringUtils.isNumeric(first)) {
                return Integer.parseInt(first);
            }
        }
    } catch (MessagingException e) {
        log.error(e.getMessage(), e);
    }

    return prio;
}