Example usage for javax.mail.internet MimeMessage MimeMessage

List of usage examples for javax.mail.internet MimeMessage MimeMessage

Introduction

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

Prototype

protected MimeMessage(Folder folder, int msgnum) 

Source Link

Document

Constructs an empty MimeMessage object with the given Folder and message number.

Usage

From source file:msgshow.java

public static void main(String argv[]) {
    int optind;//  w w w.ja va 2  s .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 {
        // 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:MainClass.java

public static void main(String argv[]) {
    int msgnum = -1;
    int optind;// w  w  w  .  j  a  v  a  2 s.  co m
    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:Controller.ReadController.java

public ReadController(String gmail_id) throws IOException, MessagingException {

    Message message = MainController.service.users().messages().get("me", gmail_id).setFormat("raw").execute();

    Base64 base64Url = new Base64(true);
    byte[] emailBytes = Base64.decodeBase64(message.getRaw());

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage mime = new MimeMessage(session, new ByteArrayInputStream(emailBytes));

    Email obj = new Email(gmail_id, mime, message.getSnippet());
    this.obj = obj;

    ReadView readView = new ReadView(this, obj);

}

From source file:com.angstoverseer.service.mail.MailServiceImpl.java

@Override
public void handleIncomingEmail(InputStream inputStream) {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    try {//from   ww w  .jav a 2 s  . c om
        MimeMessage mimeMessage = new MimeMessage(session, inputStream);

        Object messageContent = mimeMessage.getContent();
        String message;
        if (messageContent instanceof Multipart) {
            Multipart mp = (Multipart) messageContent;
            BodyPart bodyPart = mp.getBodyPart(0);
            InputStream is = bodyPart.getInputStream();
            message = convertStreamToString(is);
        } else {
            message = (String) messageContent;
        }

        Address sender = mimeMessage.getFrom()[0];
        final String commandOutput = commandService.process(message, extractEmail(sender.toString()));

        sendResponseMail(sender, commandOutput, mimeMessage.getSubject());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:Controller.MainController.java

public void populateDB()
        throws IOException, MessagingException, ClassNotFoundException, SQLException, ParseException {

    for (int i = 0; i < 10; i++) {

        String messageId = messages.get(i).getId();

        Message message = service.users().messages().get("me", messageId).setFormat("raw").execute();

        Base64 base64Url = new Base64(true);
        byte[] emailBytes = Base64.decodeBase64(message.getRaw());

        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage mime = new MimeMessage(session, new ByteArrayInputStream(emailBytes));

        Email obj = new Email(messageId, mime, message.getSnippet());

        EmailDao emailDao = new EmailDao();
        emailDao.insert(obj);//from ww w  .jav a  2  s .c om

    }

}

From source file:it.greenvulcano.gvesb.virtual.utils.MimeMessageHelper.java

public static MimeMessage decode(byte[] message) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(message));

    return email;
}

From source file:info.debatty.java.datasets.enron.Email.java

Email(final String raw, final String mailbox) throws MessagingException, Exception {
    this.raw = raw;
    String[] strings = mailbox.split(File.separator, 2);
    this.user = strings[0];
    this.mailbox = strings[1];

    Session s = Session.getDefaultInstance(new Properties());
    InputStream is = new ByteArrayInputStream(raw.getBytes());
    MimeMessage message = new MimeMessage(s, is);
    MimeMessageParser parser = new MimeMessageParser(message);

    from = parser.getFrom();/*from   w  w w  .ja  va 2  s  .com*/
    to = addressToString(parser.getTo());
    cc = addressToString(parser.getCc());
    bcc = addressToString(parser.getBcc());
    subject = parser.getSubject();
    content = parser.getPlainContent();
    message_id = parser.getMimeMessage().getMessageID();

}

From source file:com.jaeksoft.searchlib.parser.EmlParser.java

@Override
protected void parseContent(StreamLimiter streamLimiter, LanguageEnum lang)
        throws IOException, SearchLibException {
    Session session = Session.getDefaultInstance(JAVAMAIL_PROPS);
    try {//from ww w  .  j  a v  a  2 s.c om

        MimeMessage mimeMessage = new MimeMessage(session, streamLimiter.getNewInputStream());
        MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse();

        ParserResultItem result = getNewParserResultItem();
        String from = mimeMessageParser.getFrom();
        if (from != null)
            result.addField(ParserFieldEnum.email_display_from, from.toString());
        for (Address address : mimeMessageParser.getTo())
            result.addField(ParserFieldEnum.email_display_to, address.toString());
        for (Address address : mimeMessageParser.getCc())
            result.addField(ParserFieldEnum.email_display_cc, address.toString());
        for (Address address : mimeMessageParser.getBcc())
            result.addField(ParserFieldEnum.email_display_bcc, address.toString());
        result.addField(ParserFieldEnum.subject, mimeMessageParser.getSubject());
        result.addField(ParserFieldEnum.htmlSource, mimeMessageParser.getHtmlContent());
        result.addField(ParserFieldEnum.content, mimeMessageParser.getPlainContent());
        result.addField(ParserFieldEnum.email_sent_date, mimeMessage.getSentDate());
        result.addField(ParserFieldEnum.email_received_date, mimeMessage.getReceivedDate());

        for (DataSource dataSource : mimeMessageParser.getAttachmentList()) {
            result.addField(ParserFieldEnum.email_attachment_name, dataSource.getName());
            result.addField(ParserFieldEnum.email_attachment_type, dataSource.getContentType());
            if (parserSelector == null)
                continue;
            Parser attachParser = parserSelector.parseStream(getSourceDocument(), dataSource.getName(),
                    dataSource.getContentType(), null, dataSource.getInputStream(), null, null, null);
            if (attachParser == null)
                continue;
            List<ParserResultItem> parserResults = attachParser.getParserResults();
            if (parserResults != null)
                for (ParserResultItem parserResult : parserResults)
                    result.addField(ParserFieldEnum.email_attachment_content, parserResult);
        }
        if (StringUtils.isEmpty(mimeMessageParser.getHtmlContent()))
            result.langDetection(10000, ParserFieldEnum.content);
        else
            result.langDetection(10000, ParserFieldEnum.htmlSource);
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java

@DirtiesContext
@Test//w w w .  j a  va  2  s  .  co  m
public void testMarshal() throws Exception {
    Assert.assertNotNull(testShsMessage);

    resultEndpoint.expectedMessageCount(1);
    template.sendBody("direct:marshal", testShsMessage);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getReceivedExchanges();
    Exchange exchange = exchanges.get(0);

    InputStream mimeStream = exchange.getIn().getBody(InputStream.class);

    MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties()), mimeStream);
    String[] mimeSubject = mimeMessage.getHeader("Subject");
    Assert.assertTrue("SHS Message".equalsIgnoreCase(mimeSubject[0]),
            "Subject is expected to be 'SHS Message' but was " + mimeSubject[0]);

    Assert.assertNull(mimeMessage.getMessageID());

    MimeMultipart multipart = (MimeMultipart) mimeMessage.getContent();
    Assert.assertEquals(multipart.getCount(), 2);

    BodyPart bodyPart = multipart.getBodyPart(1);
    String content = (String) bodyPart.getContent();
    Assert.assertEquals(content, ShsMessageTestObjectMother.DEFAULT_TEST_BODY);

    String contentType = bodyPart.getContentType();
    Assert.assertTrue(
            StringUtils.contains(contentType, ShsMessageTestObjectMother.DEFAULT_TEST_DATAPART_CONTENTTYPE),
            "Content type error");

    String encodings[] = bodyPart.getHeader("Content-Transfer-Encoding");
    Assert.assertNotNull(encodings);
    Assert.assertEquals(encodings.length, 1);
    Assert.assertEquals(encodings[0].toUpperCase(),
            ShsMessageTestObjectMother.DEFAULT_TEST_DATAPART_TRANSFERENCODING.toString().toUpperCase());

    mimeMessage.writeTo(System.out);
}

From source file:io.kamax.mxisd.threepid.connector.email.EmailSmtpConnector.java

@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - "
                + "You must set a value for notifications to work");
    }//from  w w w . j  a  v a 2 s.co m

    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }

    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));
        msg.setHeader("X-Mailer", "mxisd"); // FIXME set version
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();

        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        transport.setStartTLS(cfg.getTls() > 0);
        transport.setRequireStartTLS(cfg.getTls() > 1);

        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        transport.connect(cfg.getHost(), cfg.getPort(), cfg.getLogin(), cfg.getPassword());
        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}