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, Authenticator authenticator) 

Source Link

Document

Get a new Session object.

Usage

From source file:org.sakaiproject.tool.mailtool.Mailtool.java

public String processSendEmail() {
    /* EmailUser */ selected = m_recipientSelector.getSelectedUsers();
    if (m_selectByTree) {
        selectedGroupAwareRoleUsers = m_recipientSelector1.getSelectedUsers();
        selectedGroupUsers = m_recipientSelector2.getSelectedUsers();
        selectedSectionUsers = m_recipientSelector3.getSelectedUsers();

        selected.addAll(selectedGroupAwareRoleUsers);
        selected.addAll(selectedGroupUsers);
        selected.addAll(selectedSectionUsers);
    }//from   www .  ja va  2  s.  c  o  m
    // Put everyone in a set so the same person doesn't get multiple emails.
    Set emailusers = new TreeSet();
    if (isAllUsersSelected()) { // the button for this is inactivated ... leave for future 
        for (Iterator i = getEmailGroups().iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            emailusers.addAll(group.getEmailusers());
        }
    }
    if (isAllGroupSelected()) {
        for (Iterator i = getEmailGroupsByType("section").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("section")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    if (isAllSectionSelected()) {
        for (Iterator i = getEmailGroupsByType("group").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("group")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    if (isAllGroupAwareRoleSelected()) {
        for (Iterator i = getEmailGroupsByType("role_groupaware").iterator(); i.hasNext();) {
            EmailGroup group = (EmailGroup) i.next();
            if (group.getEmailrole().roletype.equals("role_groupaware")) {
                selected.addAll(group.getEmailusers());
            }
        }
    }
    emailusers = new TreeSet(selected); // convert List to Set (remove duplicates)

    m_subjectprefix = getSubjectPrefixFromConfig();

    EmailUser curUser = getCurrentUser();

    String fromEmail = "";
    String fromDisplay = "";
    if (curUser != null) {
        fromEmail = curUser.getEmail();
        fromDisplay = curUser.getDisplayname();
    }
    String fromString = fromDisplay + " <" + fromEmail + ">";

    m_results = "Message sent to: <br>";

    String subject = m_subject;

    //Should we append this to the archive?
    String emailarchive = "/mailarchive/channel/" + m_siteid + "/main";
    if (m_archiveMessage && isEmailArchiveInSite()) {
        String attachment_info = "<br/>";
        Attachment a = null;
        Iterator iter = attachedFiles.iterator();
        int i = 0;
        while (iter.hasNext()) {
            a = (Attachment) iter.next();
            attachment_info += "<br/>";
            attachment_info += "Attachment #" + (i + 1) + ": " + a.getFilename() + "(" + a.getSize()
                    + " Bytes)";
            i++;
        }
        this.appendToArchive(emailarchive, fromString, subject, m_body + attachment_info);
    }
    List headers = new ArrayList();
    if (getTextFormat().equals("htmltext"))
        headers.add("content-type: text/html");
    else
        headers.add("content-type: text/plain");

    String smtp_server = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
    //String smtp_port = ServerConfigurationService.getString("smtp.port");
    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", smtp_server);
        //props.put("mail.smtp.port", smtp_port);
        Session s = Session.getInstance(props, null);

        MimeMessage message = new MimeMessage(s);

        InternetAddress from = new InternetAddress(fromString);
        message.setFrom(from);
        String reply = getReplyToSelected().trim().toLowerCase();
        if (reply.equals("yes")) {
            // "reply to sender" is default. So do nothing
        } else if (reply.equals("no")) {
            String noreply = getSiteTitle() + " <noreply@" + smtp_server + ">";
            InternetAddress noreplyemail = new InternetAddress(noreply);
            message.setFrom(noreplyemail);
        } else if (reply.equals("otheremail") && getReplyToOtherEmail().equals("") != true) {
            // need input(email) validation
            InternetAddress replytoList[] = { new InternetAddress(getConfigParam("replyto").trim()) };
            message.setReplyTo(replytoList);
        }
        message.setSubject(subject);
        String text = m_body;
        String attachmentdirectory = getUploadDirectory();

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        String messagetype = "";

        if (getTextFormat().equals("htmltext")) {
            messagetype = "text/html";
        } else {
            messagetype = "text/plain";
        }
        messageBodyPart.setContent(text, messagetype);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        Attachment a = null;
        Iterator iter = attachedFiles.iterator();
        while (iter.hasNext()) {
            a = (Attachment) iter.next();
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(
                    attachmentdirectory + this.getCurrentUser().getUserid() + "-" + a.getFilename());
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(a.getFilename());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);

        //Send the emails
        String recipientsString = "";
        for (Iterator i = emailusers.iterator(); i.hasNext(); recipientsString += ",") {
            EmailUser euser = (EmailUser) i.next();
            String toEmail = euser.getEmail(); // u.getEmail();
            String toDisplay = euser.getDisplayname(); // u.getDisplayName();
            // if AllUsers are selected, do not add current user's email to recipients
            if (isAllUsersSelected() && getCurrentUser().getEmail().equals(toEmail)) {
                // don't add sender to recipients
            } else {
                recipientsString += toEmail;
                m_results += toDisplay + (i.hasNext() ? "<br/>" : "");
            }
            //               InternetAddress to[] = {new InternetAddress(toEmail) };
            //               Transport.send(message,to);
        }
        if (m_otheremails.trim().equals("") != true) {
            //
            // multiple email validation is needed here
            //
            String refinedOtherEmailAddresses = m_otheremails.trim().replace(';', ',');
            recipientsString += refinedOtherEmailAddresses;
            m_results += "<br/>" + refinedOtherEmailAddresses;
            //               InternetAddress to[] = {new InternetAddress(refinedOtherEmailAddresses) };
            //               Transport.send(message, to);
        }
        if (m_sendmecopy) {
            message.addRecipients(Message.RecipientType.CC, fromEmail);
            // trying to solve SAK-7410
            // recipientsString+=fromEmail;
            //               InternetAddress to[] = {new InternetAddress(fromEmail) };
            //               Transport.send(message, to);
        }
        //            message.addRecipients(Message.RecipientType.TO, recipientsString);
        message.addRecipients(Message.RecipientType.BCC, recipientsString);

        Transport.send(message);
    } catch (Exception e) {
        log.debug("Mailtool Exception while trying to send the email: " + e.getMessage());
    }

    //   Clear the Subject and Body of the Message
    m_subject = getSubjectPrefix().equals("") ? getSubjectPrefixFromConfig() : getSubjectPrefix();
    m_otheremails = "";
    m_body = "";
    num_files = 0;
    attachedFiles.clear();
    m_recipientSelector = null;
    m_recipientSelector1 = null;
    m_recipientSelector2 = null;
    m_recipientSelector3 = null;
    setAllUsersSelected(false);
    setAllGroupSelected(false);
    setAllSectionSelected(false);

    //  Display Users with Bad Emails if the option is turned on.
    boolean showBadEmails = getDisplayInvalidEmailAddr();
    if (showBadEmails == true) {
        m_results += "<br/><br/>";

        List /* String */ badnames = new ArrayList();

        for (Iterator i = selected.iterator(); i.hasNext();) {
            EmailUser user = (EmailUser) i.next();
            /* This check should maybe be some sort of regular expression */
            if (user.getEmail().equals("")) {
                badnames.add(user.getDisplayname());
            }
        }
        if (badnames.size() > 0) {
            m_results += "The following users do not have valid email addresses:<br/>";
            for (Iterator i = badnames.iterator(); i.hasNext();) {
                String name = (String) i.next();
                if (i.hasNext() == true)
                    m_results += name + "/ ";
                else
                    m_results += name;
            }
        }
    }
    return "results";
}

From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java

@Override
public void send(List<String> to, List<String> cc, List<String> bcc, String subject, String body,
        List<NodeRef> attachments, boolean html) throws Exception {
    EmailConfig config = getConfig();/*from ww w  .  j  ava  2s .c  o m*/
    EmailProvider provider = getEmailProvider(config.getProviderId());
    Properties props = System.getProperties();
    String prefix = "mail." + provider.getOutgoingProto() + ".";
    props.put(prefix + "host", provider.getOutgoingServer());
    props.put(prefix + "port", provider.getOutgoingPort());
    props.put(prefix + "auth", "true");
    Session session = Session.getInstance(props, null);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(config.getAddress(), config.getRealName()));
    if (to != null) {
        InternetAddress[] recipients = new InternetAddress[to.size()];
        for (int i = 0; i < to.size(); i++)
            recipients[i] = new InternetAddress(to.get(i));
        msg.setRecipients(Message.RecipientType.TO, recipients);
    }

    if (cc != null) {
        InternetAddress[] recipients = new InternetAddress[cc.size()];
        for (int i = 0; i < cc.size(); i++)
            recipients[i] = new InternetAddress(cc.get(i));
        msg.setRecipients(Message.RecipientType.CC, recipients);
    }

    if (bcc != null) {
        InternetAddress[] recipients = new InternetAddress[bcc.size()];
        for (int i = 0; i < bcc.size(); i++)
            recipients[i] = new InternetAddress(bcc.get(i));
        msg.setRecipients(Message.RecipientType.BCC, recipients);
    }

    msg.setSubject(subject);
    msg.setHeader("X-Mailer", "Alvex Emailer");
    msg.setSentDate(new Date());

    MimeBodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();

    if (body != null) {
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body, "utf-8", html ? "html" : "plain");
        multipart.addBodyPart(messageBodyPart);
    }

    if (attachments != null)
        for (NodeRef att : attachments) {
            messageBodyPart = new MimeBodyPart();
            String fileName = (String) nodeService.getProperty(att, AlvexContentModel.PROP_EMAIL_REAL_NAME);
            messageBodyPart
                    .setDataHandler(new DataHandler(new RepositoryDataSource(att, fileName, contentService)));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        }

    msg.setContent(multipart);

    SMTPTransport t = (SMTPTransport) session.getTransport(provider.getOutgoingProto());
    t.connect(config.getUsername(), config.getPassword());
    t.sendMessage(msg, msg.getAllRecipients());
    t.close();
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Retrieves a list of all the available messages. For POP3 it checks the local mailbox and downloads any on the server.
 *  For IMAP it returns any in the INBOX.
 * @param msgList the list to be filled/*  w  ww  .j a va 2s .  co  m*/
 * @return true if not erros, false if an error occurred.
 */
public static boolean getAvailableMsgs(java.util.List<javax.mail.Message> msgList) {
    boolean status = false; // assume it will fail

    msgList.clear();

    try {
        String usernameStr = AppPreferences.getRemote().get("settings.email.username", null); //$NON-NLS-1$
        String passwordStr = Encryption
                .decrypt(AppPreferences.getRemote().get("settings.email.password", null)); //$NON-NLS-1$
        String emailStr = AppPreferences.getRemote().get("settings.email.email", null); //$NON-NLS-1$
        String smtpStr = AppPreferences.getRemote().get("settings.email.smtp", null); //$NON-NLS-1$
        String serverNameStr = AppPreferences.getRemote().get("settings.email.servername", null); //$NON-NLS-1$
        String acctTypeStr = AppPreferences.getRemote().get("settings.email.accounttype", null); //$NON-NLS-1$
        String localMailBoxStr = AppPreferences.getRemote().get("settings.email.localmailbox", null); //$NON-NLS-1$

        EMailHelper.AccountType acctType = EMailHelper.getAccountType(acctTypeStr);

        if (!hasEMailSettings(usernameStr, passwordStr, emailStr, smtpStr, serverNameStr, acctTypeStr,
                localMailBoxStr)) {
            JOptionPane.showMessageDialog(UIRegistry.getMostRecentWindow(),
                    getResourceString("EMailHelper.EMAIL_SET_NOT_VALID")); //$NON-NLS-1$
        }

        // Open Local Box if POP
        if (acctTypeStr.equals(getResourceString("EMailHelper.POP3"))) //$NON-NLS-1$
        {
            try {
                Properties props = new Properties();
                Session session = Session.getDefaultInstance(props);

                Store store = session.getStore(new URLName("mstor:" + localMailBoxStr)); //$NON-NLS-1$
                store.connect();
                status = getMessagesFromInbox(store, msgList); // closes everything

            } catch (Exception ex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex);

                instance.lastErrorMsg = ex.toString();
                ex.printStackTrace();
                status = false;
            }
        } else {
            throw new RuntimeException("Unknown Account Type [" + acctTypeStr + "] must be POP3 or IMAP"); // XXX FIXME //$NON-NLS-1$ //$NON-NLS-2$
        }

        // Try to download message from pop account
        try {
            Properties props = System.getProperties();
            Session session = Session.getInstance(props, null);

            if (acctType == AccountType.POP3) {
                Store store = session.getStore("pop3"); //$NON-NLS-1$
                store.connect(serverNameStr, usernameStr, passwordStr);
                status = getMessagesFromInbox(store, msgList); // closes everything

            } else if (acctType == AccountType.IMAP) {
                Store store = session.getStore("imap"); //$NON-NLS-1$
                store.connect(serverNameStr, usernameStr, passwordStr);
                status = getMessagesFromInbox(store, msgList); // closes everything

            } else {
                String msgStr = getResourceString("EMailHelper.UNKNOWN_ACCT_TYPE")// //$NON-NLS-1$
                        + acctTypeStr + getResourceString("EMailHelper.ACCT_TYPE_MUST_BE"); // XXX// //$NON-NLS-2$

                instance.lastErrorMsg = msgStr;
                throw new RuntimeException(msgStr); // XXX FIXME
            }
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex);
            instance.lastErrorMsg = ex.toString();
            status = false;
        }

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex);
        instance.lastErrorMsg = ex.toString();
        status = false;
    }
    return status;
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Send a Collection of Mails (multiple emails)
 * // ww  w .j a  v a  2  s .  c  om
 * @param emails Mail Collection
 * @return True in any case (TODO ?)
 */
public boolean sendMails(Collection<Mail> emails, MailConfiguration mailConfiguration, XWikiContext context)
        throws MessagingException, UnsupportedEncodingException {
    Session session = null;
    Transport transport = null;
    int emailCount = emails.size();
    int count = 0;
    int sendFailedCount = 0;
    try {
        for (Iterator<Mail> emailIt = emails.iterator(); emailIt.hasNext();) {
            count++;

            Mail mail = emailIt.next();
            LOGGER.info("Sending email: " + mail.toString());

            if ((transport == null) || (session == null)) {
                // initialize JavaMail Session and Transport
                Properties props = initProperties(mailConfiguration);
                session = Session.getInstance(props, null);
                transport = session.getTransport("smtp");
                if (!mailConfiguration.usesAuthentication()) {
                    // no auth info - typical 127.0.0.1 open relay scenario
                    transport.connect();
                } else {
                    // auth info present - typical with external smtp server
                    transport.connect(mailConfiguration.getSmtpUsername(), mailConfiguration.getSmtpPassword());
                }
            }

            try {
                MimeMessage message = createMimeMessage(mail, session, context);
                if (message == null) {
                    continue;
                }

                transport.sendMessage(message, message.getAllRecipients());

                // close the connection every other 100 emails
                if ((count % 100) == 0) {
                    try {
                        if (transport != null) {
                            transport.close();
                        }
                    } catch (MessagingException ex) {
                        LOGGER.error("MessagingException has occured.", ex);
                    }
                    transport = null;
                    session = null;
                }
            } catch (SendFailedException ex) {
                sendFailedCount++;
                LOGGER.error("SendFailedException has occured.", ex);
                LOGGER.error("Detailed email information" + mail.toString());
                if (emailCount == 1) {
                    throw ex;
                }
                if ((emailCount != 1) && (sendFailedCount > 10)) {
                    throw ex;
                }
            } catch (MessagingException mex) {
                LOGGER.error("MessagingException has occured.", mex);
                LOGGER.error("Detailed email information" + mail.toString());
                if (emailCount == 1) {
                    throw mex;
                }
            } catch (XWikiException e) {
                LOGGER.error("XWikiException has occured.", e);
            } catch (IOException e) {
                LOGGER.error("IOException has occured.", e);
            }
        }
    } finally {
        try {
            if (transport != null) {
                transport.close();
            }
        } catch (MessagingException ex) {
            LOGGER.error("MessagingException has occured.", ex);
        }

        LOGGER.info("sendEmails: Email count = " + emailCount + " sent count = " + count);
    }
    return true;
}

From source file:org.exoplatform.chat.server.ChatServer.java

public void sendMailWithAuth(String senderFullname, List<String> toList, String htmlBody, String subject)
        throws Exception {

    String host = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_HOST);
    String user = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_USER);
    String password = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PASSWORD);
    String port = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PORT);

    Properties props = System.getProperties();

    props.put("mail.smtp.user", user);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    //props.put("mail.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.EnableSSL.enable", "true");

    Session session = Session.getInstance(props, null);
    //session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(user, senderFullname));

    // To get the array of addresses
    for (String to : toList) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    }//from   w  w  w .ja v a 2 s .c  o m

    message.setSubject(subject);
    message.setContent(htmlBody, "text/html");

    Transport transport = session.getTransport("smtp");
    try {
        transport.connect(host, user, password);
        transport.sendMessage(message, message.getAllRecipients());
    } finally {
        transport.close();
    }
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server/*from  w  w w. ja va 2 s.c  o m*/
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static boolean sendMsgAsGMail(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, @SuppressWarnings("unused") final String port,
        @SuppressWarnings("unused") final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;
    Boolean fail = false;

    ArrayList<String> userAndPass = new ArrayList<String>();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host); //$NON-NLS-1$
    props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    boolean usingSSL = false;
    if (usingSSL) {
        props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
        props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    }

    Session session = Session.getInstance(props, null);

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
    }

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));
        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            InternetAddress[] address = { new InternetAddress(toEMailAddr) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

            // create the Multipart and add its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);

            // add the Multipart to the message
            msg.setContent(mp);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

        // set the Date: header
        msg.setSentDate(new Date());

        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                t.connect(host, userName, password);

                t.sendMessage(msg, msg.getAllRecipients());

                fail = false;
            } catch (MessagingException mex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
                instance.lastErrorMsg = mex.toString();

                Exception ex = null;
                if ((ex = mex.getNextException()) != null) {
                    ex.printStackTrace();
                    instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
                }

                //wrong username or password, get new one
                if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    fail = true;
                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) {//the user is done
                        return false;
                    }
                    // else
                    //try again
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }
            } finally {

                log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                t.close();
            }
        } while (fail && cnt < 6);

    } catch (MessagingException mex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        //mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return false;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex);
        ex.printStackTrace();
    }

    if (fail) {
        return false;
    } //else
    return true;
}

From source file:net.spfbl.core.Analise.java

private static Object getResponseSMTP(String host, int port, int timeout) {
    try {/* w w w.  j  a v  a  2 s. c o m*/
        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "false");
        props.put("mail.smtp.auth", "false");
        props.put("mail.smtp.timeout", Integer.toString(timeout));
        props.put("mail.smtp.connectiontimeout", "3000");
        Session session = Session.getInstance(props, null);
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        try {
            transport.setLocalHost(Core.getHostname());
            transport.connect(host, port, null, null);
            String response = transport.getLastServerResponse();
            int beginIndex = 4;
            int endIndex;
            for (endIndex = beginIndex; endIndex < response.length(); endIndex++) {
                if (response.charAt(endIndex) == ' ') {
                    break;
                } else if (response.charAt(endIndex) == '\n') {
                    break;
                }
            }
            String helo = response.substring(beginIndex, endIndex);
            if (helo.contains(".") && Domain.isHostname(helo)) {
                return Domain.normalizeHostname(helo, true);
            } else {
                return null;
            }
        } finally {
            if (transport.isConnected()) {
                transport.close();
            }
        }
    } catch (MailConnectException ex) {
        if (ex.getMessage().contains("timeout -1")) {
            return Status.CLOSED;
        } else {
            return Status.TIMEOUT;
        }
    } catch (MessagingException ex) {
        //            if (ex.getMessage().containsExact("TLS")) {
        //                return Status.NOTLS;
        //            } else {
        return Status.UNAVAILABLE;
        //            }
    } catch (Exception ex) {
        Server.logError(ex);
        return null;
    }
}

From source file:au.aurin.org.controller.RestController.java

private Session getSession() {
    final Authenticator authenticator = new Authenticator();

    final Properties properties = new Properties();
    properties.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
    properties.setProperty("mail.smtp.auth", classmail.getAuth().toString());

    properties.setProperty("mail.smtp.host", classmail.getHost());
    properties.setProperty("mail.smtp.port", classmail.getPort());

    return Session.getInstance(properties, authenticator);
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Verifies the signature of the passed signed part*/
public MimeBodyPart verifySignedPart(Part signedPart, byte[] data, String contentType,
        X509Certificate certificate) throws Exception {
    BCCryptoHelper helper = new BCCryptoHelper();
    String signatureTransferEncoding = null;
    MimeMultipart checkPart = (MimeMultipart) signedPart.getContent();
    //it is sure that it is a signed part: set the type to multipart if the
    //parser has problems parsing it. Don't know why sometimes a parsing fails for
    //MimeBodyPart. This check looks if the parser is able to find more than one subpart
    if (checkPart.getCount() == 1) {
        MimeMultipart multipart = new MimeMultipart(new ByteArrayDataSource(data, contentType));
        MimeMessage possibleSignedMessage = new MimeMessage(Session.getInstance(System.getProperties(), null));
        possibleSignedMessage.setContent(multipart, multipart.getContentType());
        possibleSignedMessage.saveChanges();
        //overwrite the formerly found signed part
        signedPart = helper.getSignedEmbeddedPart(possibleSignedMessage);
    }/*from w w w  .  j  av  a 2s . c  o m*/
    //get the content encoding of the signature
    MimeMultipart signedMultiPart = (MimeMultipart) signedPart.getContent();
    //body part 1 is always the signature
    String encodingHeader[] = signedMultiPart.getBodyPart(1).getHeader("Content-Transfer-Encoding");
    if (encodingHeader != null) {
        signatureTransferEncoding = encodingHeader[0];
    }
    return (helper.verify(signedPart, signatureTransferEncoding, certificate));
}

From source file:smilehouse.opensyncro.pipes.Pipe.java

private void addLogEntry(LogEntry logEntry, int statusCode) {
    if (this.log == null)
        this.log = new HashSet();

    logEntry.setStatusCode(statusCode);// w w  w  .  j a  v  a  2  s.  c  om
    logEntry.setTime(new Date());

    // The LogEntry is not explicitly added to the Pipe's log Set, since it causes
    // Hibernate to query all LogEntries from the database and thus consume
    // ever-increasing amount of server resources.

    //this.log.add(logEntry);
    String status = getStatusString(statusCode);

    Persister persister = new Persister(database);

    try {
        persister.update(logEntry);

        List messages;

        boolean mailAddressNotSet = ((getMailHost() == null || getRecipientAddress() == null)
                || (getMailHost().length() == 0 || getRecipientAddress().length() == 0));

        // Notification via email only if host and email address are present
        if (!mailAddressNotSet && !(getTransferLogNotificationLevel() == MessageLogger.MAIL_NONE)) {

            String date = dateFormat.format(new Date());
            String subject = this.getName() + " " + status + " " + date + " (" + database + ")";
            String message = "";

            // Get number of log messages at or below transferLogNotificationLevel.  

            int entries = persister.getLogMessageEntries(logEntry.getId(), getTransferLogNotificationLevel())
                    .size();

            //Generate mail message
            if (entries > 0) {

                messages = persister.getLogMessageEntries(logEntry.getId(), getLoggingVerbosityLevel());
                for (Iterator m = messages.iterator(); m.hasNext();) {
                    LogMessageEntry messageEntry = (LogMessageEntry) m.next();
                    message += (messageEntry.getMessage()) + "\n";
                }
            } else {
                message += MAIL_MESSAGE_NO_ENTRIES;
            }

            // Send notification email except when the message is
            // MAIL_MESSAGE_NO_ENTRIES or the pipe has aborted and 
            // isAbortMailEnabled()==true 
            if (!message.equals(MAIL_MESSAGE_NO_ENTRIES)
                    || (statusCode == LogEntry.STATUS_ABORTED && isAbortMailEnabled())) {
                try {

                    Properties props = new Properties();
                    props.put("mail.host", getMailHost());

                    Session mailConnection = Session.getInstance(props, null);
                    Message msg = new MimeMessage(mailConnection);
                    Address sender = new InternetAddress(MAIL_SENDER + "@" + getMailHost(), MAIL_SENDER);
                    Address[] receivers = receiverAddresses(getRecipientAddress());

                    // Set mail content and subject
                    msg.setContent(message, "text/plain");
                    msg.setFrom(sender);
                    msg.setRecipients(Message.RecipientType.TO, receivers);
                    msg.setSubject(subject);

                    // Send the mail
                    Transport.send(msg);

                } catch (MessagingException e) {
                    String error = "An error occurred when sending mail report from " + MAIL_SENDER + "@"
                            + getMailHost() + " to " + getRecipientAddress() + ":\n" + e.getMessage();
                    Environment.getInstance().log(error);
                    logEntry.logMessage(error, this, MessageLogger.ERROR);
                    persister.update(logEntry);
                } catch (RuntimeException ex) {
                    Environment.getInstance().log("A RuntimeException has occurred: " + ex.getMessage()
                            + ex.getStackTrace().toString());
                }
            }
        }
        // Remove unnecessary (debug level) messages from the LogEntry if Transfer log
        // verbosity level is set to DYNAMIC and the current LogEntry's status is either
        // OK or ABORTED
        if (getLoggingVerbosityLevel() == MessageLogger.LOG_DYNAMIC
                && (statusCode == LogEntry.STATUS_OK || statusCode == LogEntry.STATUS_ABORTED)) {
            messages = persister.getLogMessageEntries(logEntry.getId(), MessageLogger.DEBUG);
            if (messages.size() > 0) {
                for (Iterator m = messages.iterator(); m.hasNext();) {
                    LogMessageEntry messageEntry = (LogMessageEntry) m.next();
                    if (messageEntry.getMessageType() == MessageLogger.DEBUG) {
                        persister.delete(messageEntry);

                    }
                }
            }
        }
    } catch (Exception e) {
        Environment.getInstance().log(e.getMessage());
    } finally {
        persister.close();
    }
}