Example usage for javax.mail Session getDefaultInstance

List of usage examples for javax.mail Session getDefaultInstance

Introduction

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

Prototype

public static Session getDefaultInstance(Properties props) 

Source Link

Document

Get the default Session object.

Usage

From source file:org.usergrid.rest.management.RegistrationIT.java

private Message[] getMessages(String host, String user, String password)
        throws MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());
    Store store = session.getStore("imap");
    store.connect(host, user, password);

    Folder folder = store.getFolder("inbox");
    folder.open(Folder.READ_ONLY);//w w  w .jav  a  2 s  .c o  m
    Message[] msgs = folder.getMessages();

    for (Message m : msgs) {
        logger.info("Subject: " + m.getSubject());
        logger.info("Body content 0 " + (String) ((MimeMultipart) m.getContent()).getBodyPart(0).getContent());
        logger.info("Body content 1 " + (String) ((MimeMultipart) m.getContent()).getBodyPart(1).getContent());
    }
    return msgs;
}

From source file:org.apache.usergrid.rest.management.RegistrationIT.java

private Message[] getMessages(String host, String user, String password)
        throws MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());
    Store store = session.getStore("imap");
    store.connect(host, user, password);

    Folder folder = store.getFolder("inbox");
    folder.open(Folder.READ_ONLY);//from  w  ww .  j  av  a2 s  . c  o m
    Message[] msgs = folder.getMessages();

    for (Message m : msgs) {
        logger.info("Subject: " + m.getSubject());
        logger.info("Body content 0 " + ((MimeMultipart) m.getContent()).getBodyPart(0).getContent());
        logger.info("Body content 1 " + ((MimeMultipart) m.getContent()).getBodyPart(1).getContent());
    }
    return msgs;
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void testMessageRenamedBetweenReads() throws Exception {
    // Get test message UID
    final Long uid = getMessageUid(folder, 1);
    // Get Message size
    final int count = getMessageSize(folder, uid);

    // Get first part
    // Split the message into 2 part using a non multiple of 4 - 103 is a prime number
    // as the BASE64Decoder may not throw the IOException
    // see MNT-12995
    BODY body = getMessageBodyPart(folder, uid, 0, count - 103);

    // Rename message. The size of letter describing the node will change
    // These changes should be committed because it should be visible from client
    NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE);
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();//from   ww w  .ja v a2  s .co  m
    fileFolderService.rename(contentNode, "testtesttesttesttesttesttesttesttesttest");
    txn.commit();

    // Read second message part
    BODY bodyRest = getMessageBodyPart(folder, uid, count - 103, 103);

    // Creating and parsing message from 2 parts
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()),
            new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()),
                    new BufferedInputStream(bodyRest.getByteArrayInputStream())));

    // Reading first part - should be successful
    MimeMultipart content = (MimeMultipart) message.getContent();
    assertNotNull(content.getBodyPart(0).getContent());

    try {
        // Reading second part cause error
        content.getBodyPart(1).getContent();
        fail("Should raise an IOException");
    } catch (IOException e) {
    }
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void dontTestMessageCache() throws Exception {

    // Create messages
    NodeRef contentNode = findNode(companyHomePathInStore + TEST_FILE);
    UserTransaction txn = transactionService.getUserTransaction();
    txn.begin();//from  w  ww  .  j a v  a 2  s .c  om

    // Create messages more than cache capacity
    for (int i = 0; i < 51; i++) {
        FileInfo fi = fileFolderService.create(nodeService.getParentAssocs(contentNode).get(0).getParentRef(),
                "test" + i, ContentModel.TYPE_CONTENT);
        ContentWriter writer = fileFolderService.getWriter(fi.getNodeRef());
        writer.putContent("test");
    }

    txn.commit();

    // Reload folder
    folder.close(false);
    folder = (IMAPFolder) store.getFolder(TEST_FOLDER);
    folder.open(Folder.READ_ONLY);

    // Read all messages
    for (int i = 1; i < 51; i++) {
        // Get test message UID
        final Long uid = getMessageUid(folder, i);
        // Get Message size
        final int count = getMessageSize(folder, uid);

        // Get first part
        BODY body = getMessageBodyPart(folder, uid, 0, count - 100);
        // Read second message part
        BODY bodyRest = getMessageBodyPart(folder, uid, count - 100, 100);

        // Creating and parsing message from 2 parts
        MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()),
                new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()),
                        new BufferedInputStream(bodyRest.getByteArrayInputStream())));

        // Reading first part - should be successful
        MimeMultipart content = (MimeMultipart) message.getContent();
        assertNotNull(content.getBodyPart(0).getContent());
        assertNotNull(content.getBodyPart(1).getContent());
    }
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void testUnmodifiedMessage() throws Exception {
    // Get test message UID
    final Long uid = getMessageUid(folder, 1);
    // Get Message size
    final int count = getMessageSize(folder, uid);

    // Make multiple message reading
    for (int i = 0; i < 100; i++) {
        // Get random offset
        int n = (int) ((int) 100 * Math.random());

        // Get first part
        BODY body = getMessageBodyPart(folder, uid, 0, count - n);
        // Read second message part
        BODY bodyRest = getMessageBodyPart(folder, uid, count - n, n);

        // Creating and parsing message from 2 parts
        MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()),
                new SequenceInputStream(new BufferedInputStream(body.getByteArrayInputStream()),
                        new BufferedInputStream(bodyRest.getByteArrayInputStream())));

        MimeMultipart content = (MimeMultipart) message.getContent();
        // Reading first part - should be successful
        assertNotNull(content.getBodyPart(0).getContent());
        // Reading second part - should be successful
        assertNotNull(content.getBodyPart(1).getContent());
    }//from w ww.j  a  v  a2s  .  co  m
}

From source file:org.alfresco.email.server.EmailServiceImplTest.java

/**
  * ALF-9544//from ww  w  .  ja  v  a2  s . com
  * ALF-751 
  *  
  * Inbound email to a folder restricts file name to 86 characters or less.
  * 
  * Also has tests for other variations of subject
  */
public void testFolderSubject() throws Exception {
    logger.debug("Start testFromName");

    String TEST_EMAIL = "buffy@sunnydale.high";

    folderEmailMessageHandler.setOverwriteDuplicates(true);

    // TODO Investigate why setting PROP_EMAIL on createPerson does not work.
    NodeRef person = personService.getPerson(TEST_USER);
    if (person == null) {
        logger.debug("new person created");
        Map<QName, Serializable> props = new HashMap<QName, Serializable>();
        props.put(ContentModel.PROP_USERNAME, TEST_USER);
        props.put(ContentModel.PROP_EMAIL, TEST_EMAIL);
        person = personService.createPerson(props);
    }
    nodeService.setProperty(person, ContentModel.PROP_EMAIL, TEST_EMAIL);

    Set<String> auths = authorityService.getContainedAuthorities(null, "GROUP_EMAIL_CONTRIBUTORS", true);
    if (!auths.contains(TEST_USER)) {
        authorityService.addAuthority("GROUP_EMAIL_CONTRIBUTORS", TEST_USER);
    }

    String companyHomePathInStore = "/app:company_home";
    String storePath = "workspace://SpacesStore";
    StoreRef storeRef = new StoreRef(storePath);

    NodeRef storeRootNodeRef = nodeService.getRootNode(storeRef);
    List<NodeRef> nodeRefs = searchService.selectNodes(storeRootNodeRef, companyHomePathInStore, null,
            namespaceService, false);
    NodeRef companyHomeNodeRef = nodeRefs.get(0);
    assertNotNull("company home is null", companyHomeNodeRef);
    String companyHomeDBID = ((Long) nodeService.getProperty(companyHomeNodeRef, ContentModel.PROP_NODE_DBID))
            .toString() + "@Alfresco.com";
    String testUserDBID = ((Long) nodeService.getProperty(person, ContentModel.PROP_NODE_DBID)).toString()
            + "@Alfresco.com";
    NodeRef testUserHomeFolder = (NodeRef) nodeService.getProperty(person, ContentModel.PROP_HOMEFOLDER);
    assertNotNull("testUserHomeFolder is null", testUserHomeFolder);
    String testUserHomeDBID = ((Long) nodeService.getProperty(testUserHomeFolder, ContentModel.PROP_NODE_DBID))
            .toString() + "@Alfresco.com";

    /**
     * Send From the test user TEST_EMAIL to the test user's home
     */
    String from = TEST_EMAIL;
    String to = testUserHomeDBID;
    String content = "hello world";

    {
        Session sess = Session.getDefaultInstance(new Properties());
        assertNotNull("sess is null", sess);
        SMTPMessage msg = new SMTPMessage(sess);
        InternetAddress[] toa = { new InternetAddress(to) };

        msg.setFrom(new InternetAddress(TEST_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, toa);
        msg.setSubject(
                "This is a very very long name in particular it is greater than eitghty six characters which was a problem explored in ALF-9544");
        msg.setContent(content, "text/plain");

        StringBuffer sb = new StringBuffer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(bos);
        InputStream is = IOUtils.toInputStream(bos.toString());
        assertNotNull("is is null", is);

        SubethaEmailMessage m = new SubethaEmailMessage(is);
        EmailDelivery delivery = new EmailDelivery(to, from, null);

        emailService.importMessage(delivery, m);
    }

    // Check import with subject containing some "illegal chars"
    {
        Session sess = Session.getDefaultInstance(new Properties());
        assertNotNull("sess is null", sess);
        SMTPMessage msg = new SMTPMessage(sess);
        InternetAddress[] toa = { new InternetAddress(to) };

        msg.setFrom(new InternetAddress(TEST_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, toa);
        msg.setSubject("Illegal<>!*/\\.txt");
        msg.setContent(content, "text/plain");

        StringBuffer sb = new StringBuffer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(bos);
        InputStream is = IOUtils.toInputStream(bos.toString());
        assertNotNull("is is null", is);

        SubethaEmailMessage m = new SubethaEmailMessage(is);
        EmailDelivery delivery = new EmailDelivery(to, from, null);

        emailService.importMessage(delivery, m);
    }

    // Check with null subject
    {
        Session sess = Session.getDefaultInstance(new Properties());
        assertNotNull("sess is null", sess);
        SMTPMessage msg = new SMTPMessage(sess);
        InternetAddress[] toa = { new InternetAddress(to) };

        msg.setFrom(new InternetAddress(TEST_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, toa);
        //msg.setSubject();
        msg.setContent(content, "text/plain");

        StringBuffer sb = new StringBuffer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(bos);
        InputStream is = IOUtils.toInputStream(bos.toString());
        assertNotNull("is is null", is);

        SubethaEmailMessage m = new SubethaEmailMessage(is);
        EmailDelivery delivery = new EmailDelivery(to, from, null);

        emailService.importMessage(delivery, m);
    }

    // ALF-751 Email ends with period
    {
        Session sess = Session.getDefaultInstance(new Properties());
        assertNotNull("sess is null", sess);
        SMTPMessage msg = new SMTPMessage(sess);
        InternetAddress[] toa = { new InternetAddress(to) };

        msg.setFrom(new InternetAddress(TEST_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, toa);
        msg.setSubject("Foobar.");
        msg.setContent(content, "text/plain");

        StringBuffer sb = new StringBuffer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(bos);
        InputStream is = IOUtils.toInputStream(bos.toString());
        assertNotNull("is is null", is);

        SubethaEmailMessage m = new SubethaEmailMessage(is);
        EmailDelivery delivery = new EmailDelivery(to, from, null);

        emailService.importMessage(delivery, m);
    }

    // ALF-751 Email ends with ...
    {
        Session sess = Session.getDefaultInstance(new Properties());
        assertNotNull("sess is null", sess);
        SMTPMessage msg = new SMTPMessage(sess);
        InternetAddress[] toa = { new InternetAddress(to) };

        msg.setFrom(new InternetAddress(TEST_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, toa);
        msg.setSubject("Foobar...");
        msg.setContent(content, "text/plain");

        StringBuffer sb = new StringBuffer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(bos);
        InputStream is = IOUtils.toInputStream(bos.toString());
        assertNotNull("is is null", is);

        SubethaEmailMessage m = new SubethaEmailMessage(is);
        EmailDelivery delivery = new EmailDelivery(to, from, null);

        emailService.importMessage(delivery, m);
    }

    // ALF-751 Email subject is blank " ... "
    {
        Session sess = Session.getDefaultInstance(new Properties());
        assertNotNull("sess is null", sess);
        SMTPMessage msg = new SMTPMessage(sess);
        InternetAddress[] toa = { new InternetAddress(to) };

        msg.setFrom(new InternetAddress(TEST_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, toa);
        msg.setSubject(" ... ");
        msg.setContent(content, "text/plain");

        StringBuffer sb = new StringBuffer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(bos);
        InputStream is = IOUtils.toInputStream(bos.toString());
        assertNotNull("is is null", is);

        SubethaEmailMessage m = new SubethaEmailMessage(is);
        EmailDelivery delivery = new EmailDelivery(to, from, null);

        emailService.importMessage(delivery, m);
    }

    // ALF-751 Email subject is a single .
    {
        Session sess = Session.getDefaultInstance(new Properties());
        assertNotNull("sess is null", sess);
        SMTPMessage msg = new SMTPMessage(sess);
        InternetAddress[] toa = { new InternetAddress(to) };

        msg.setFrom(new InternetAddress(TEST_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, toa);
        msg.setSubject(".");
        msg.setContent(content, "text/plain");

        StringBuffer sb = new StringBuffer();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        msg.writeTo(bos);
        InputStream is = IOUtils.toInputStream(bos.toString());
        assertNotNull("is is null", is);

        SubethaEmailMessage m = new SubethaEmailMessage(is);
        EmailDelivery delivery = new EmailDelivery(to, from, null);

        emailService.importMessage(delivery, m);
    }

}

From source file:network.thunder.server.etc.Tools.java

public static void emailException(Exception e, Message m, Channel c, Payment p, Transaction channelTransaction,
        Transaction t) {/*from w  w w .j  a v a 2s .  c  o m*/
    String to = "matsjj@gmail.com";
    String from = "exception@thunder.network";
    String host = "localhost";
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(properties);

    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));

        message.setSubject("New Critical Exception thrown..");

        String text = "";

        text += Tools.stacktraceToString(e);
        text += "\n";
        if (m != null) {
            text += m;
        }
        text += "\n";
        if (c != null) {
            text += c;
        }
        text += "\n";
        if (p != null) {
            text += p;
        }
        text += "\n";
        if (channelTransaction != null) {
            text += channelTransaction;
        }
        text += "\n";
        if (t != null) {
            text += t;
        }

        // Now set the actual message
        message.setText(text);

        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
        //           mex.printStackTrace();
    }
}

From source file:org.alfresco.repo.imap.ImapMessageTest.java

public void testEncodedFromToAddresses() throws Exception {
    // RFC1342//  w w w  .  ja v  a  2  s  . c  o m
    String addressString = "ars.kov@gmail.com";
    String personalString = "?? ";
    InternetAddress address = new InternetAddress(addressString, personalString, "UTF-8");

    // Following method returns the address with quoted personal aka <["?? "] <ars.kov@gmail.com>>
    // NOTE! This should be coincided with RFC822MetadataExtracter. Would 'addresses' be quoted or not? 
    // String decodedAddress = address.toUnicodeString();
    // So, just using decode, for now
    String decodedAddress = MimeUtility.decodeText(address.toString());

    // InternetAddress.toString(new Address[] {address}) - is used in the RFC822MetadataExtracter
    // So, compare with that
    assertFalse("Non ASCII characters in the address should be encoded",
            decodedAddress.equals(InternetAddress.toString(new Address[] { address })));

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMessageHelper messageHelper = new MimeMessageHelper(message, false, "UTF-8");

    messageHelper.setText("This is a sample message for ALF-5647");
    messageHelper.setSubject("This is a sample message for ALF-5647");
    messageHelper.setFrom(address);
    messageHelper.addTo(address);
    messageHelper.addCc(address);

    // Creating the message node in the repository
    String name = AlfrescoImapConst.MESSAGE_PREFIX + GUID.generate();
    FileInfo messageFile = fileFolderService.create(testImapFolderNodeRef, name, ContentModel.TYPE_CONTENT);
    // Writing a content.
    new IncomingImapMessage(messageFile, serviceRegistry, message);

    // Getting the transformed properties from the repository
    // cm:originator, cm:addressee, cm:addressees, imap:messageFrom, imap:messageTo, imap:messageCc
    Map<QName, Serializable> properties = nodeService.getProperties(messageFile.getNodeRef());

    String cmOriginator = (String) properties.get(ContentModel.PROP_ORIGINATOR);
    String cmAddressee = (String) properties.get(ContentModel.PROP_ADDRESSEE);
    @SuppressWarnings("unchecked")
    List<String> cmAddressees = (List<String>) properties.get(ContentModel.PROP_ADDRESSEES);
    String imapMessageFrom = (String) properties.get(ImapModel.PROP_MESSAGE_FROM);
    String imapMessageTo = (String) properties.get(ImapModel.PROP_MESSAGE_TO);
    String imapMessageCc = (String) properties.get(ImapModel.PROP_MESSAGE_CC);

    assertNotNull(cmOriginator);
    assertEquals(decodedAddress, cmOriginator);
    assertNotNull(cmAddressee);
    assertEquals(decodedAddress, cmAddressee);
    assertNotNull(cmAddressees);
    assertEquals(1, cmAddressees.size());
    assertEquals(decodedAddress, cmAddressees.get(0));
    assertNotNull(imapMessageFrom);
    assertEquals(decodedAddress, imapMessageFrom);
    assertNotNull(imapMessageTo);
    assertEquals(decodedAddress, imapMessageTo);
    assertNotNull(imapMessageCc);
    assertEquals(decodedAddress, imapMessageCc);
}

From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java

private MimeMessage prepareMimeMessage(String subject) throws MessagingException {
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    message.setSubject(subject);//  ww  w.j a  v  a2s .  c o  m
    message.setSender(new InternetAddress(USER));
    message.setRecipient(RecipientType.TO, new InternetAddress(SIEVE_LOCALHOST));
    message.saveChanges();
    return message;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

public SetMessageResponseType archiveMessage(SetMessageRequestType request) {
    SetMessageResponseType response = new SetMessageResponseType();

    IMAPSSLStore sslStore = null;//  w w w. ja  v a2  s  . c o  m
    Folder folder = null;
    Folder destinationFolder = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    // INPUT:  request.getUserId()
    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDAO contactDAO = LdapService.getContactDAO();
    ContactDTO foundContact = new ContactDTO();
    List<ContactDTO> contacts = contactDAO.findAllContacts();
    for (ContactDTO contact : contacts) {
        if (contact.getUid() != null && contact.getUid().equals(request.getUserId())) {
            foundContact = contact;
            break;
        }
    }

    String userType = "";
    String[] access = new String[2];
    String userCName = foundContact.getCommonName();
    if (contacts.isEmpty()) {
        log.error("Contact record not found for user: " + userCName);
        response.setMessage("Contact record not found for user: " + userCName);
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(userCName, foundContact.getUid()); //TMN

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    //PROCESSING the action.
    // folder --> the current folder the msg being processed is in.
    // destinationFolder --> the destination folder where the msg will be moved.
    try {

        //----------------------------------
        // Determine/Set destination folder
        //----------------------------------
        if (request.getAction().equals("Archive")) {
            destinationFolder = getImapFolder(session, sslStore, access, "Archives");
        } else if (request.getAction().equals("Unarchive")) {
            destinationFolder = getImapFolder(session, sslStore, access, "INBOX");
        }
        destinationFolder.open(Folder.READ_WRITE);

        //----------------------------------
        // Set originating folder
        //----------------------------------
        folder = getImapFolder(session, sslStore, access,
                this.mapKmrLocationToImapFolder(request.getLocation(), this.host));
        folder.open(Folder.READ_WRITE);

        System.out.println(
                "===> DMD.archiveMessage: " + request.getAction() + "-ing for msgId=" + request.getMessageId()
                        + "\n===> from " + folder.getName() + " to folder=" + destinationFolder.getName());

        //--------------------------------------------
        // Find the message by the given Message-ID
        //--------------------------------------------
        IMAPMessage imapMessage = (IMAPMessage) findMsgByMessageId(folder, request.getMessageId());

        //--------------------------------------------
        // Process the message
        //--------------------------------------------
        if (imapMessage != null) {
            Message[] messages = new Message[] { imapMessage };
            folder.copyMessages(messages, destinationFolder);
            imapMessage.setFlag(Flags.Flag.DELETED, true);
            folder.expunge();

            System.out.println("===> DMD.archiveMessage: Done " + request.getAction() + " for msgId="
                    + request.getMessageId());

            response.setSuccessStatus(true);

        } else {
            String statMsg = "Msg NOT found for Message-ID=" + request.getMessageId();
            System.out.println("===> " + statMsg);

            response.setSuccessStatus(false);
            response.setMessage(statMsg);
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage(
                "Error " + request.getAction() + " mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        e.printStackTrace();
        return response;

    } finally {
        try {
            if ((folder != null) && folder.isOpen())
                folder.close(false);
            if ((destinationFolder != null) && destinationFolder.isOpen())
                destinationFolder.close(false);
        } catch (MessagingException me) {
            me.printStackTrace();
        }
    }

    return response;
}