Example usage for javax.mail Session getInstance

List of usage examples for javax.mail Session getInstance

Introduction

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

Prototype

public static Session getInstance(Properties props) 

Source Link

Document

Get a new Session object.

Usage

From source file:gov.nih.nci.firebird.service.messages.email.EmailServiceImplTest.java

@Test
public void testSendMessageInvalidSessionPortNonNumeric() {
    props.setProperty(Email.MAIL_PORT, "not a number");
    bean.setMailSession(Session.getInstance(props));
    bean.sendMessage(TEST_TO_ADDRESS, null, null, testMessage);
    assertFalse(mailbox.isEmpty());/*from   w ww .  java  2s . co  m*/
}

From source file:edu.umich.ctools.sectionsUtilityTool.Friend.java

public static void notifyCurrentUser(String instructorName, String instructorEmail, String inviteEmail) {

    M_log.debug("Friend notifyCurrentUser() called");
    String to = instructorEmail;/*from w w w  .ja  v  a2 s.co m*/
    String from = contactEmail;
    String host = mailHost;

    M_log.info("Setting up mailProps");

    Properties properties = System.getProperties();
    properties.put(MAIL_SMTP_AUTH, "false");
    properties.put(MAIL_SMTP_STARTTLS, "true"); //Put to false, if no https is needed
    properties.put(MAIL_SMTP_HOST, host);
    properties.put(MAIL_DEBUG, "true");

    M_log.debug("Initiating Session for sendMail");
    Session session = Session.getInstance(properties);

    try {

        HashMap<String, String> map = new HashMap<String, String>();

        map.put("<instructor>", instructorName);
        map.put("<friend>", inviteEmail);

        emailMessage = Friend.readFile(requesterEmailFile, StandardCharsets.UTF_8);
        emailMessage = replacePlaceHolders(emailMessage, map);

        M_log.debug("Setting up message for sendMail");
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subjectLine);

        message.setText(emailMessage);

        M_log.info("Sending message");
        Transport.send(message);

        M_log.info("Message sent to " + instructorName);

    } catch (Exception e) {
        M_log.error("notifyCurrentUser exception: " + e.getMessage());
    }
}

From source file:net.sourceforge.vulcan.mailer.EmailPlugin.java

private void createMailSession() {
    final String smtpHost = config.getSmtpHost();

    if (smtpHost != null && smtpHost.length() > 0) {
        final Properties props = new Properties();

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

        mailSession = Session.getInstance(props);
    } else {//from   www.j  a  v a  2 s.  co  m
        mailSession = null;
    }
    messageAssembler.setMailSession(mailSession);
}

From source file:org.xwiki.mail.integration.JavaIntegrationTest.java

@Test
public void sendMailWithCustomMessageId() throws Exception {
    Session session = Session.getInstance(this.configuration.getAllProperties());
    MimeMessage message = new MimeMessage(session) {
        @Override// w  ww.  ja  v a  2  s . c o  m
        protected void updateMessageID() throws MessagingException {
            if (getMessageID() == null) {
                super.updateMessageID();
            }
        }
    };
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));
    message.setText("Test message Id support");
    message.setHeader("Message-ID", "<custom@domain>");
    message.setSubject("subject");

    MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory");
    this.sender.sendAsynchronously(Arrays.asList(message), session, memoryMailListener);

    // Verify that the mails have been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 1);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    assertEquals("<custom@domain>", messages[0].getMessageID());
}

From source file:org.apache.james.core.builder.MimeMessageBuilder.java

public MimeMessage build() throws MessagingException {
    Preconditions.checkState(!(text.isPresent() && content.isPresent()),
            "Can not get at the same time a text and a content");
    MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties()));
    if (text.isPresent()) {
        mimeMessage.setContent(text.get(), textContentType.orElse(DEFAULT_TEXT_PLAIN_UTF8_TYPE));
    }// w w w .j  a  va  2s  .c  o  m
    if (content.isPresent()) {
        mimeMessage.setContent(content.get());
    }
    if (sender.isPresent()) {
        mimeMessage.setSender(sender.get());
    }
    if (subject.isPresent()) {
        mimeMessage.setSubject(subject.get());
    }
    ImmutableList<InternetAddress> fromAddresses = from.build();
    if (!fromAddresses.isEmpty()) {
        mimeMessage.addFrom(fromAddresses.toArray(new InternetAddress[fromAddresses.size()]));
    }
    List<InternetAddress> toAddresses = to.build();
    if (!toAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.TO,
                toAddresses.toArray(new InternetAddress[toAddresses.size()]));
    }
    List<InternetAddress> ccAddresses = cc.build();
    if (!ccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.CC,
                ccAddresses.toArray(new InternetAddress[ccAddresses.size()]));
    }
    List<InternetAddress> bccAddresses = bcc.build();
    if (!bccAddresses.isEmpty()) {
        mimeMessage.setRecipients(Message.RecipientType.BCC,
                bccAddresses.toArray(new InternetAddress[bccAddresses.size()]));
    }

    MimeMessage wrappedMessage = MimeMessageWrapper.wrap(mimeMessage);

    List<Header> headerList = headers.build();
    for (Header header : headerList) {
        if (header.name.equals("Message-ID") || header.name.equals("Date")) {
            wrappedMessage.setHeader(header.name, header.value);
        } else {
            wrappedMessage.addHeader(header.name, header.value);
        }
    }
    wrappedMessage.saveChanges();

    return wrappedMessage;
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void renameMailbox(final Properties props, final String folderName, final String user,
        final String password) throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

    store.connect(user, password);/*  w  w  w  .j a v  a 2  s.c o m*/
    checkStoreForTestConnection(store);
    final Folder f = store.getFolder(folderName);

    f.renameTo(store.getFolder("renamed_from_" + folderName));

    logger.info("Renamed " + f.getFullName());
    store.close();

}

From source file:de.saly.elasticsearch.mailsource.ParallelPollingIMAPMailSource.java

protected void fetch(final Pattern pattern, final String folderName) throws MessagingException, IOException {

    logger.debug("fetch() - pattern: {}, folderName: {}", pattern, folderName);

    final Store store = Session.getInstance(props).getStore();
    store.connect(user, password);/*ww  w .j  a  v a 2  s  .  c o  m*/

    try {
        for (final String fol : mailDestination.getFolderNames()) {
            if (store.getFolder(fol).exists()) {
                logger.debug("{} exists", fol);
            } else {
                logger.info(
                        "Folder {} does not exist on the server, will remove it (and its content) also locally",
                        fol);
                final RiverState riverState = stateManager.getRiverState(store.getFolder(fol));
                riverState.setExists(false);
                stateManager.setRiverState(riverState);

                try {
                    mailDestination.clearDataForFolder(fol);
                } catch (final Exception e) {
                    stateManager.onError("Unable to clean data for stale folder", store.getFolder(fol), e);
                }
            }
        }
    } catch (final IndexMissingException ime) {
        logger.debug(ime.toString());

    } catch (final Exception e) {
        logger.error("Error checking for stale folders", e);
    }

    final boolean isRoot = StringUtils.isEmpty(folderName);
    final Folder folder = isRoot ? store.getDefaultFolder() : store.getFolder(folderName);

    try {

        if (!folder.exists()) {
            logger.error("Folder {} does not exist on the server", folder.getFullName());
            return;
        }

        logger.debug("folderName: {} is root: {}", folderName, isRoot);

        /*if (logger.isDebugEnabled() && store instanceof IMAPStore) {
                
           IMAPStore imapStore = (IMAPStore) store;
           logger.debug("IMAP server capability info");
           logger.debug("IMAP4rev1: "
             + imapStore.hasCapability("IMAP4rev1"));
           logger.debug("IDLE: " + imapStore.hasCapability("IDLE"));
           logger.debug("ID: " + imapStore.hasCapability("ID"));
           logger.debug("UIDPLUS: " + imapStore.hasCapability("UIDPLUS"));
           logger.debug("CHILDREN: " + imapStore.hasCapability("CHILDREN"));
           logger.debug("NAMESPACE: "
             + imapStore.hasCapability("NAMESPACE"));
           logger.debug("NOTIFY: " + imapStore.hasCapability("NOTIFY"));
           logger.debug("CONDSTORE: "
             + imapStore.hasCapability("CONDSTORE"));
           logger.debug("QRESYNC: " + imapStore.hasCapability("QRESYNC"));
           logger.debug("STATUS: " + imapStore.hasCapability("STATUS"));
        }*/

        if (pattern != null && !isRoot && !pattern.matcher(folder.getFullName()).matches()) {
            logger.info(folder.getFullName() + " does not match pattern " + pattern.toString());
            return;
        }

        IMAPUtils.open(folder);

        recurseFolders(folder, pattern);

    } finally {

        IMAPUtils.close(folder);
        IMAPUtils.close(store);

    }
}

From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java

protected void fetch(final Pattern pattern, final String folderName) throws MessagingException, IOException {
    logger.debug("fetch() - pattern: {}, folderName: {}, user: {}", pattern, folderName, user);

    final Store store = Session.getInstance(props).getStore();
    store.connect(user, password);//  w w w  .  j a  v  a2s . co  m

    if (deleteExpungedMessages) {

        try {
            for (final String fol : mailDestination.getFolderNames()) {
                if (store.getFolder(fol).exists()) {
                    logger.debug("{} exists for {}", fol, user);
                } else {
                    logger.info(
                            "Folder {} does not exist for {} on the server, will remove it (and its content) also locally",
                            user, fol);
                    final State riverState = stateManager.getRiverState(store.getFolder(fol));
                    riverState.setExists(false);
                    stateManager.setRiverState(riverState);

                    try {
                        mailDestination.clearDataForFolder(store.getFolder(fol));
                    } catch (final Exception e) {
                        stateManager.onError("Unable to clean data for stale folder for " + user,
                                store.getFolder(fol), e);
                    }
                }
            }
        } /*catch (final IndexMissingException ime) {
          logger.debug(ime.toString());
          //TODO 2.0 check
          } */ catch (final Exception e) {
            logger.error("Error checking for stale folders", e);
        }

    }

    final boolean isRoot = StringUtils.isEmpty(folderName);
    final Folder folder = isRoot ? store.getDefaultFolder() : store.getFolder(folderName);

    try {

        if (!folder.exists()) {
            logger.error("Folder {} does not exist on the server", folder.getFullName());
            return;
        }

        logger.debug("folderName: {} is root: {}", folderName, isRoot);

        /*if (logger.isDebugEnabled() && store instanceof IMAPStore) {
                
           IMAPStore imapStore = (IMAPStore) store;
           logger.debug("IMAP server capability info");
           logger.debug("IMAP4rev1: "
             + imapStore.hasCapability("IMAP4rev1"));
           logger.debug("IDLE: " + imapStore.hasCapability("IDLE"));
           logger.debug("ID: " + imapStore.hasCapability("ID"));
           logger.debug("UIDPLUS: " + imapStore.hasCapability("UIDPLUS"));
           logger.debug("CHILDREN: " + imapStore.hasCapability("CHILDREN"));
           logger.debug("NAMESPACE: "
             + imapStore.hasCapability("NAMESPACE"));
           logger.debug("NOTIFY: " + imapStore.hasCapability("NOTIFY"));
           logger.debug("CONDSTORE: "
             + imapStore.hasCapability("CONDSTORE"));
           logger.debug("QRESYNC: " + imapStore.hasCapability("QRESYNC"));
           logger.debug("STATUS: " + imapStore.hasCapability("STATUS"));
        }*/

        if (pattern != null && !isRoot && !pattern.matcher(folder.getFullName()).matches()) {
            logger.debug(folder.getFullName() + " does not match pattern " + pattern.toString());
            return;
        }

        IMAPUtils.open(folder);

        recurseFolders(folder, pattern);

    } finally {

        IMAPUtils.close(folder);
        IMAPUtils.close(store);

    }
}

From source file:com.consol.citrus.mail.server.MailServer.java

/**
 * Return new mail session if not already created before.
 * @return/*  w ww  .ja va2s. c  om*/
 */
public synchronized Session getSession() {
    if (this.mailSession == null) {
        this.mailSession = Session.getInstance(this.javaMailProperties);
    }
    return this.mailSession;
}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

public void sendMailMessagingException(InternetAddress from, InternetAddress[] to, String subject,
        String content, Map<RecipientType, InternetAddress[]> headerTo, InternetAddress[] replyTo,
        List<String> additionalHeaders, List<Attachment> attachments) throws MessagingException {
    // some timing for debug
    long start = 0;
    if (M_log.isDebugEnabled())
        start = System.currentTimeMillis();

    // if in test mode, use the test method
    if (m_testMode) {
        testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders);
        return;//  w ww  . j a va2 s . c  o  m
    }

    if (m_smtp == null) {
        M_log.error(
                "Unable to send mail as no smtp server is defined. Please set smtp@org.sakaiproject.email.api.EmailService value in sakai.properties");
        return;
    }

    if (from == null) {
        M_log.warn("sendMail: null from");
        return;
    }

    if (to == null) {
        M_log.warn("sendMail: null to");
        return;
    }

    if (content == null) {
        M_log.warn("sendMail: null content");
        return;
    }

    Properties props = createMailSessionProperties();

    Session session = Session.getInstance(props);

    // see if we have a message-id in the additional headers
    String mid = null;
    if (additionalHeaders != null) {
        for (String header : additionalHeaders) {
            if (header.toLowerCase().startsWith(EmailHeaders.MESSAGE_ID.toLowerCase() + ": ")) {
                // length of 'message-id: ' == 12
                mid = header.substring(12);
                break;
            }
        }
    }

    // use the special extension that can set the id
    MimeMessage msg = new MyMessage(session, mid);

    // the FULL content-type header, for example:
    // Content-Type: text/plain; charset=windows-1252; format=flowed
    String contentTypeHeader = null;

    // If we need to force the container to use a certain multipart subtype
    //    e.g. 'alternative'
    // then sneak it through in the additionalHeaders
    String multipartSubtype = null;

    // set the additional headers on the message
    // but treat Content-Type specially as we need to check the charset
    // and we already dealt with the message id
    if (additionalHeaders != null) {
        for (String header : additionalHeaders) {
            if (header.toLowerCase().startsWith(EmailHeaders.CONTENT_TYPE.toLowerCase() + ": "))
                contentTypeHeader = header;
            else if (header.toLowerCase().startsWith(EmailHeaders.MULTIPART_SUBTYPE.toLowerCase() + ": "))
                multipartSubtype = header.substring(header.indexOf(":") + 1).trim();
            else if (!header.toLowerCase().startsWith(EmailHeaders.MESSAGE_ID.toLowerCase() + ": "))
                msg.addHeaderLine(header);
        }
    }

    // date
    if (msg.getHeader(EmailHeaders.DATE) == null)
        msg.setSentDate(new Date(System.currentTimeMillis()));

    // set the message sender
    msg.setFrom(from);

    // set the message recipients (headers)
    setRecipients(headerTo, msg);

    // set the reply to
    if ((replyTo != null) && (msg.getHeader(EmailHeaders.REPLY_TO) == null))
        msg.setReplyTo(replyTo);

    // update to be Postmaster if necessary
    checkFrom(msg);

    // figure out what charset encoding to use
    //
    // first try to use the charset from the forwarded
    // Content-Type header (if there is one).
    //
    // if that charset doesn't work, try a couple others.
    // the character set, for example, windows-1252 or UTF-8
    String charset = extractCharset(contentTypeHeader);

    if (charset != null && canUseCharset(content, charset) && canUseCharset(subject, charset)) {
        // use the charset from the Content-Type header
    } else if (canUseCharset(content, CharacterSet.ISO_8859_1)
            && canUseCharset(subject, CharacterSet.ISO_8859_1)) {
        if (contentTypeHeader != null && charset != null)
            contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.ISO_8859_1);
        else if (contentTypeHeader != null)
            contentTypeHeader += "; charset=" + CharacterSet.ISO_8859_1;
        charset = CharacterSet.ISO_8859_1;
    } else if (canUseCharset(content, CharacterSet.WINDOWS_1252)
            && canUseCharset(subject, CharacterSet.WINDOWS_1252)) {
        if (contentTypeHeader != null && charset != null)
            contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.WINDOWS_1252);
        else if (contentTypeHeader != null)
            contentTypeHeader += "; charset=" + CharacterSet.WINDOWS_1252;
        charset = CharacterSet.WINDOWS_1252;
    } else {
        // catch-all - UTF-8 should be able to handle anything
        if (contentTypeHeader != null && charset != null)
            contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.UTF_8);
        else if (contentTypeHeader != null)
            contentTypeHeader += "; charset=" + CharacterSet.UTF_8;
        else
            contentTypeHeader = EmailHeaders.CONTENT_TYPE + ": " + ContentType.TEXT_PLAIN + "; charset="
                    + CharacterSet.UTF_8;
        charset = CharacterSet.UTF_8;
    }

    if ((subject != null) && (msg.getHeader(EmailHeaders.SUBJECT) == null))
        msg.setSubject(subject, charset);

    // extract just the content type value from the header
    String contentType = null;
    if (contentTypeHeader != null) {
        int colonPos = contentTypeHeader.indexOf(":");
        contentType = contentTypeHeader.substring(colonPos + 1).trim();
    }
    setContent(content, attachments, msg, contentType, charset, multipartSubtype);

    // if we have a full Content-Type header, set it NOW
    // (after setting the body of the message so that format=flowed is preserved)
    // if there attachments, the messsage type will default to multipart/mixed and should
    // stay that way.
    if ((attachments == null || attachments.size() == 0) && contentTypeHeader != null) {
        msg.addHeaderLine(contentTypeHeader);
        msg.addHeaderLine(EmailHeaders.CONTENT_TRANSFER_ENCODING + ": quoted-printable");
    }

    if (M_log.isDebugEnabled()) {
        M_log.debug("HeaderLines received were: ");
        Enumeration<String> allHeaders = msg.getAllHeaderLines();
        while (allHeaders.hasMoreElements()) {
            M_log.debug((String) allHeaders.nextElement());
        }
    }

    sendMessageAndLog(from, to, subject, headerTo, start, msg, session);
}