Example usage for org.apache.commons.mail Email setPopBeforeSmtp

List of usage examples for org.apache.commons.mail Email setPopBeforeSmtp

Introduction

In this page you can find the example usage for org.apache.commons.mail Email setPopBeforeSmtp.

Prototype

public void setPopBeforeSmtp(final boolean newPopBeforeSmtp, final String newPopHost,
        final String newPopUsername, final String newPopPassword) 

Source Link

Document

Set details regarding "pop3 before smtp" authentication.

Usage

From source file:com.aurel.track.util.emailHandling.MailSender.java

private Email setAuthMode(Email email) {
    Integer smtpAuthMode = new Integer(-1);
    try {/*from www.ja v  a 2  s .  com*/
        smtpAuthMode = Integer.valueOf(smtpMailSettings.getAuthMode());
    } catch (Exception e) {
    }

    switch (smtpAuthMode) {
    case TSiteBean.SMTP_AUTHENTICATION_MODES.CONNECT_TO_INCOMING_MAIL_SERVER_BEFORE_SENDING: {
        IncomingMailSettings incomingMailSettings = smtpMailSettings.getIncomingMailSettings();
        String mailReceivingServerName = null;
        String mailReceivingUser = null;
        String mailReceivingPassword = null;
        if (incomingMailSettings != null) {
            mailReceivingServerName = incomingMailSettings.getServerName();
            mailReceivingUser = incomingMailSettings.getUser();
            mailReceivingPassword = incomingMailSettings.getPassword();
        }
        boolean newPopBeforeSmtp = true; // TODO We should check in our POP3 session first
        email.setPopBeforeSmtp(newPopBeforeSmtp, mailReceivingServerName, mailReceivingUser,
                mailReceivingPassword);
        break;
    }

    case TSiteBean.SMTP_AUTHENTICATION_MODES.CONNECT_USING_SMTP_SETTINGS: {
        LOGGER.debug("Connect to SMTP server using SMTP user/password ...");
        if (smtpMailSettings.getUser() == null || "".equals(smtpMailSettings.getUser().trim())) {
            LOGGER.warn("No SMTP user found by 'Connect using SMTP settings'");
        }
        email.setAuthenticator(
                new DefaultAuthenticator(smtpMailSettings.getUser(), smtpMailSettings.getPassword()));
        break;
    }

    case TSiteBean.SMTP_AUTHENTICATION_MODES.CONNECT_WITH_SAME_SETTINGS_AS_INCOMING_MAIL_SERVER: {
        IncomingMailSettings incomingMailSettings = smtpMailSettings.getIncomingMailSettings();
        String mailReceivingUser = null;
        String mailReceivingPassword = null;
        if (incomingMailSettings != null) {
            mailReceivingUser = incomingMailSettings.getUser();
            mailReceivingPassword = incomingMailSettings.getPassword();
        }
        LOGGER.debug("Connect to SMTP server using incoming mail (POP3 or IMAP) user " + mailReceivingUser
                + " passord specified "
                + new Boolean(mailReceivingPassword != null && mailReceivingPassword.length() > 0).toString());
        if (mailReceivingUser == null || "".equals(mailReceivingUser.trim())) {
            LOGGER.warn(
                    "No incoming mail user (POP3 or IMAP) found by 'Connect with same settings as incoming mail server'");
        }
        email.setAuthenticator(new DefaultAuthenticator(mailReceivingUser, mailReceivingPassword));
        break;
    }
    }
    return email;
}

From source file:org.jwebsocket.plugins.mail.MailPlugIn.java

private void sendMail(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();//from  w w  w  .  ja  v  a2 s .co  m

    String lFrom = aToken.getString("from", "[unknown]");
    String lTo = aToken.getString("to");
    String lCC = aToken.getString("cc");
    String lBCC = aToken.getString("bcc");
    String lSubject = aToken.getString("subject");
    String lBody = aToken.getString("body");
    Boolean lIsHTML = aToken.getBoolean("html", false);

    // instantiate response token
    Token lResponse = lServer.createResponse(aToken);

    Map lMap = new FastMap();

    if (lFrom != null && lFrom.length() > 0) {
        lMap.put("from", lFrom);
    }
    if (lTo != null && lTo.length() > 0) {
        lMap.put("to", lTo);
    }
    if (lCC != null && lCC.length() > 0) {
        lMap.put("cc", lCC);
    }
    if (lBCC != null && lBCC.length() > 0) {
        lMap.put("bcc", lBCC);
    }
    if (lSubject != null && lSubject.length() > 0) {
        lMap.put("subject", lSubject);
    }
    if (lBody != null && lBody.length() > 0) {
        lMap.put("body", lBody);
    }

    // Create the attachment
    List<EmailAttachment> lAttachments = new FastList<EmailAttachment>();
    /*
    if( aAttachments != null  ) {
    for( int lIdx = 0; lIdx < aAttachments.length; lIdx++  ) {
    EmailAttachment lAttachment = new EmailAttachment();
    lAttachment.setPath( aAttachments[ lIdx ] );
    lAttachment.setDisposition( EmailAttachment.ATTACHMENT );
    // lAttachment.setDescription( "Picture of John" );
    // lAttachment.setName( "John" );
    lAttachments.add( lAttachment );
    }
    }
     */
    // Create the lEmail message
    if (mLog.isDebugEnabled()) {
        mLog.debug("Sending e-mail to " + lTo + " with subject '" + lSubject + "'...");
    }
    try {
        Email lEmail;
        if (lIsHTML) {
            lEmail = new HtmlEmail();
        } else {
            lEmail = new MultiPartEmail();
        }

        lEmail.setHostName(SMTP_HOST);
        lEmail.setSmtpPort(SMTP_PORT);
        if (SMTP_AUTH) {
            lEmail.setAuthentication(SMTP_USER, SMTP_PASSWORD);
        }
        if (SMTP_POP3BEFORE) {
            lEmail.setPopBeforeSmtp(true, POP3_HOST, POP3_USER, POP3_PASSWORD);
        }
        if (lFrom != null && lFrom.length() > 0) {
            lEmail.setFrom(lFrom);
        }
        if (lTo != null && lTo.length() > 0) {
            lEmail.addTo(lTo);
        }
        if (lSubject != null && lSubject.length() > 0) {
            lEmail.setSubject(lSubject);
        }

        if (lBody != null && lBody.length() > 0) {
            if (lIsHTML) {
                HtmlEmail lHTML = ((HtmlEmail) lEmail);
                /*
                URL lURL = new URL("http://five-feet-further.com/aschulze/images/portrait_web_kleiner.jpg");
                String lCID = ((HtmlEmail )lEmail).embed(lURL, "five feet further logo");
                        
                //url = new URL( "http://five-feet-further.com/resources/css/IJX4FWDocu.css" );
                // String css = ((HtmlEmail)lEmail).embed( url, "name of css" );
                        
                ((HtmlEmail )lEmail).setHtmlMsg(
                "<html><body>" +
                "<style type=\"text/css\">" +
                "h1 { " +
                " font-family:arial, helvetica, sans-serif;" +
                " font-weight:bold;" +
                " font-size:18pt;" +
                "}" +
                "</style>" +
                // "<link href=\"cid:" + css + "\" type=\"text/css\" rel=\"stylesheet\">" +
                "<p><img src=\"cid:" + lCID + "\"></p>" +
                "<p><img src=\"http://five-feet-further.com/aschulze/images/portrait_web_kleiner.jpg\"></p>" +
                lItem +
                "</body></html>");
                 */

                /*
                // Now the message body.
                Multipart mp = new MimeMultipart();
                        
                BodyPart textPart = new MimeBodyPart();
                // sets type to "text/plain"
                textPart.setText("Kann Ihr Browser keine HTML-Mails darstellen?");
                        
                BodyPart pixPart = new MimeBodyPart();
                pixPart.setContent(lMsg, "text/html");
                        
                // Collect the Parts into the MultiPart
                mp.addBodyPart(textPart);
                mp.addBodyPart(pixPart);
                        
                // Put the MultiPart into the Message
                ((HtmlEmail) lEmail).setContent((MimeMultipart)mp);
                ((HtmlEmail) lEmail).buildMimeMessage();
                        
                /*
                // ((HtmlEmail) lEmail).setContent(lMsg, Email.TEXT_HTML);
                        
                // lHeaders.put("Innotrade-Id", "4711-0815");
                // lHTML.setHeaders(lHeaders);
                // ((HtmlEmail) lEmail).setCharset("UTF-8");
                // ((HtmlEmail) lEmail).setMsg(lMsg);
                lMM.setHeader("Innotrade-Id", "4711-0815");
                        
                // ((HtmlEmail) lEmail).setContent(lTxtMsg, Email.TEXT_PLAIN);
                 */
                // String lTxtMsg = "Your Email-Client does not support HTML messages.";
                lHTML.setHtmlMsg(lBody);
                // lHTML.setTextMsg(lTxtMsg);
            } else {
                lEmail.setMsg(lBody);
            }
        }

        // add attachment(s), if such
        for (EmailAttachment lAttachment : lAttachments) {
            ((MultiPartEmail) lEmail).attach(lAttachment);
        }

        for (int lIdx = 0; lIdx < lAttachments.size(); lIdx++) {
            ((MultiPartEmail) lEmail).attach((EmailAttachment) lAttachments.get(lIdx));
        }

        // send the Email
        String lMsgId = lEmail.send();

        if (mLog.isInfoEnabled()) {
            mLog.info("Email successfully sent" + " from " + (lFrom != null ? lFrom : "(no sender)") + " to "
                    + (lTo != null ? lTo : "(no receipient)") + ", subject "
                    + (lSubject != null ? "'" + lSubject + "'" : "(no subject)") + ", Id " + lMsgId);
        }

        lResponse.setString("id", lMsgId);
    } catch (Exception lEx) {
        String lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage();
        mLog.error(lMsg);
        lResponse.setInteger("code", -1);
        lResponse.setString("msg", lMsg);
    }

    // send response to requester
    lServer.sendToken(aConnector, lResponse);
}

From source file:org.jwebsocket.plugins.mail.MailPlugInService.java

/**
 *
 * @param aToken/*from ww w .j  a  v a  2 s. c o m*/
 * @return
 */
public Token sendMail(Token aToken) {
    String lFrom = aToken.getString("from", "[unknown]");
    String lTo = aToken.getString("to");
    String lCC = aToken.getString("cc");
    String lBCC = aToken.getString("bcc");
    String lSubject = aToken.getString("subject");
    String lBody = aToken.getString("body");
    Boolean lIsHTML = aToken.getBoolean("html", false);
    List<Object> lAttachedFiles = aToken.getList("attachments");
    String lMsg;

    // instantiate response token
    Token lResponse = TokenFactory.createToken();

    Map<String, String> lMap = new FastMap<String, String>();

    if (lFrom != null && lFrom.length() > 0) {
        lMap.put("from", lFrom);
    }
    if (lTo != null && lTo.length() > 0) {
        lMap.put("to", lTo);
    }
    if (lCC != null && lCC.length() > 0) {
        lMap.put("cc", lCC);
    }
    if (lBCC != null && lBCC.length() > 0) {
        lMap.put("bcc", lBCC);
    }
    if (lSubject != null && lSubject.length() > 0) {
        lMap.put("subject", lSubject);
    }
    if (lBody != null && lBody.length() > 0) {
        lMap.put("body", lBody);
    }

    // Create the attachment
    List<EmailAttachment> lEmailAttachments = new FastList<EmailAttachment>();

    if (lAttachedFiles != null) {
        for (Object lAttachedFile : lAttachedFiles) {
            EmailAttachment lAttachment = new EmailAttachment();
            lAttachment.setPath((String) lAttachedFile);
            lAttachment.setDisposition(EmailAttachment.ATTACHMENT);
            // lAttachment.setDescription( "Picture of John" );
            // lAttachment.setName( "John" );
            lEmailAttachments.add(lAttachment);
        }
    }

    // Create the lEmail message
    if (mLog.isDebugEnabled()) {
        mLog.debug("Sending e-mail to " + lTo + " with subject '" + lSubject + "'...");
    }
    try {
        Email lEmail;
        if (lIsHTML) {
            lEmail = new HtmlEmail();
        } else {
            lEmail = new MultiPartEmail();
        }

        lEmail.setHostName(mSettings.getSmtpHost());
        lEmail.setSmtpPort(mSettings.getSmtpPort());
        if (mSettings.getSmtpAuth()) {
            lEmail.setAuthentication(mSettings.getSmtpUser(), mSettings.getSmtpPassword());
        }
        if (mSettings.getSmtpPop3Before()) {
            lEmail.setPopBeforeSmtp(true, mSettings.getPop3Host(), mSettings.getPop3User(),
                    mSettings.getPop3Password());
        }
        if (lFrom != null && lFrom.length() > 0) {
            lEmail.setFrom(lFrom);
        }
        if (lTo != null && lTo.length() > 0) {
            String[] lToSplit = lTo.split(";");
            for (String lToSplit1 : lToSplit) {
                if (lToSplit1 != null && lToSplit1.length() > 0) {
                    lEmail.addTo(lToSplit1.trim());
                }
            }
        }
        if (lCC != null && lCC.length() > 0) {
            String[] lCCSplit = lCC.split(";");
            for (String lCCSplit1 : lCCSplit) {
                if (lCCSplit1 != null && lCCSplit1.length() > 0) {
                    lEmail.addCc(lCCSplit1.trim());
                }
            }
        }
        if (lBCC != null && lBCC.length() > 0) {
            String[] lBCCSplit = lBCC.split(";");
            for (String lBCCSplit1 : lBCCSplit) {
                if (lBCCSplit1 != null && lBCCSplit1.length() > 0) {
                    lEmail.addBcc(lBCCSplit1.trim());
                }
            }
        }
        if (lSubject != null && lSubject.length() > 0) {
            lEmail.setSubject(lSubject);
        }

        if (lBody != null && lBody.length() > 0) {
            if (lIsHTML) {
                HtmlEmail lHTML = ((HtmlEmail) lEmail);
                /*
                 * URL lURL = new
                 * URL("http://five-feet-further.com/aschulze/images/portrait_web_kleiner.jpg");
                 * String lCID = ((HtmlEmail )lEmail).embed(lURL, "five feet
                 * further logo");
                 *
                 * //url = new URL(
                 * "http://five-feet-further.com/resources/css/IJX4FWDocu.css"
                 * ); // String css = ((HtmlEmail)lEmail).embed( url, "name
                 * of css" );
                 *
                 * ((HtmlEmail )lEmail).setHtmlMsg( "<html><body>" + "<style
                 * type=\"text/css\">" + "h1 { " + " font-family:arial,
                 * helvetica, sans-serif;" + " font-weight:bold;" + "
                 * font-size:18pt;" + "}" + "</style>" + // "<link
                 * href=\"cid:" + css + "\" type=\"text/css\"
                 * rel=\"stylesheet\">" + "<p><img src=\"cid:" + lCID +
                 * "\"></p>" + "<p><img
                 * src=\"http://five-feet-further.com/aschulze/images/portrait_web_kleiner.jpg\"></p>"
                 * + lItem + "</body></html>");
                 */

                /*
                 * // Now the message body. Multipart mp = new
                 * MimeMultipart();
                 *
                 * BodyPart textPart = new MimeBodyPart(); // sets type to
                 * "text/plain" textPart.setText("Kann Ihr Browser keine
                 * HTML-Mails darstellen?");
                 *
                 * BodyPart pixPart = new MimeBodyPart();
                 * pixPart.setContent(lMsg, "text/html");
                 *
                 * // Collect the Parts into the MultiPart
                 * mp.addBodyPart(textPart); mp.addBodyPart(pixPart);
                 *
                 * // Put the MultiPart into the Message ((HtmlEmail)
                 * lEmail).setContent((MimeMultipart)mp); ((HtmlEmail)
                 * lEmail).buildMimeMessage();
                 *
                 * /*
                 * // ((HtmlEmail) lEmail).setContent(lMsg,
                 * Email.TEXT_HTML);
                 *
                 * // lHeaders.put("Innotrade-Id", "4711-0815"); //
                 * lHTML.setHeaders(lHeaders); // ((HtmlEmail)
                 * lEmail).setCharset("UTF-8"); // ((HtmlEmail)
                 * lEmail).setMsg(lMsg); lMM.setHeader("Innotrade-Id",
                 * "4711-0815");
                 *
                 * // ((HtmlEmail) lEmail).setContent(lTxtMsg,
                 * Email.TEXT_PLAIN);
                 */
                // String lTxtMsg = "Your Email-Client does not support HTML messages.";
                lHTML.setHtmlMsg(lBody);
                // lHTML.setTextMsg(lTxtMsg);
            } else {
                lEmail.setMsg(lBody);
            }
        }

        // add attachment(s), if such
        for (EmailAttachment lAttachment : lEmailAttachments) {
            ((MultiPartEmail) lEmail).attach(lAttachment);
        }

        // send the Email
        String lMsgId = lEmail.send();

        if (mLog.isInfoEnabled()) {
            lMsg = "Email successfully sent" + " from " + (lFrom != null ? lFrom : "(no sender)") + " to "
                    + (lTo != null ? lTo : "(no recipient)") + " cc " + (lCC != null ? lCC : "(no recipient)")
                    + ", subject " + (lSubject != null ? "'" + lSubject + "'" : "(no subject)") + ", msgId "
                    + lMsgId;
            mLog.info(lMsg);
        }
        lResponse.setInteger("code", 0);
        lResponse.setString("msg", "ok");
        lResponse.setString("msgId", lMsgId);
    } catch (EmailException lEx) {
        lMsg = lEx.getClass().getSimpleName() + " (" + lEx.getCause().getClass().getSimpleName() + "): "
                + lEx.getMessage();
        mLog.error(lMsg);
        lResponse.setInteger("code", -1);
        lResponse.setString("msg", lMsg);
    }
    return lResponse;
}

From source file:org.openhab.action.mail.internal.Mail.java

/**
 * Sends an email with attachment(s) via SMTP
 * /*  w w  w  . j  av a 2s .c  o  m*/
 * @param to the email address of the recipient
 * @param subject the subject of the email
 * @param message the body of the email
 * @param attachmentUrlList a list of URL strings of the contents to send as attachments
 * 
 * @return <code>true</code>, if sending the email has been successful and 
 * <code>false</code> in all other cases.
 */
@ActionDoc(text = "Sends an email with attachment via SMTP")
static public boolean sendMail(@ParamDoc(name = "to") String to, @ParamDoc(name = "subject") String subject,
        @ParamDoc(name = "message") String message,
        @ParamDoc(name = "attachmentUrlList") List<String> attachmentUrlList) {
    boolean success = false;
    if (MailActionService.isProperlyConfigured) {
        Email email = new SimpleEmail();
        if (attachmentUrlList != null && !attachmentUrlList.isEmpty()) {
            email = new MultiPartEmail();
            for (String attachmentUrl : attachmentUrlList) {
                // Create the attachment
                try {
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setURL(new URL(attachmentUrl));
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    String fileName = attachmentUrl.replaceFirst(".*/([^/?]+).*", "$1");
                    attachment.setName(StringUtils.isNotBlank(fileName) ? fileName : "Attachment");
                    ((MultiPartEmail) email).attach(attachment);
                } catch (MalformedURLException e) {
                    logger.error("Invalid attachment url.", e);
                } catch (EmailException e) {
                    logger.error("Error adding attachment to email.", e);
                }
            }
        }

        email.setHostName(hostname);
        email.setSmtpPort(port);
        email.setTLS(tls);

        if (StringUtils.isNotBlank(username)) {
            if (popBeforeSmtp) {
                email.setPopBeforeSmtp(true, hostname, username, password);
            } else {
                email.setAuthenticator(new DefaultAuthenticator(username, password));
            }
        }

        try {
            if (StringUtils.isNotBlank(charset)) {
                email.setCharset(charset);
            }
            email.setFrom(from);
            String[] toList = to.split(";");
            for (String toAddress : toList) {
                email.addTo(toAddress);
            }
            if (!StringUtils.isEmpty(subject))
                email.setSubject(subject);
            if (!StringUtils.isEmpty(message))
                email.setMsg(message);
            email.send();
            logger.debug("Sent email to '{}' with subject '{}'.", to, subject);
            success = true;
        } catch (EmailException e) {
            logger.error("Could not send e-mail to '" + to + "'.", e);
        }
    } else {
        logger.error(
                "Cannot send e-mail because of missing configuration settings. The current settings are: "
                        + "Host: '{}', port '{}', from '{}', useTLS: {}, username: '{}', password '{}'",
                new Object[] { hostname, String.valueOf(port), from, String.valueOf(tls), username, password });
    }

    return success;
}

From source file:org.openhab.io.net.actions.Mail.java

/**
 * Sends an email with attachment via SMTP
 * //from   w  w w. j a v a 2 s  . co m
 * @param to the email address of the recipient
 * @param subject the subject of the email
 * @param message the body of the email
 * @param attachmentUrl a URL string of the content to send as an attachment
 * 
 * @return <code>true</code>, if sending the email has been successful and 
 * <code>false</code> in all other cases.
 */
static public boolean sendMail(String to, String subject, String message, String attachmentUrl) {
    boolean success = false;
    if (initialized) {
        Email email = new SimpleEmail();
        if (attachmentUrl != null) {
            // Create the attachment
            try {
                email = new MultiPartEmail();
                EmailAttachment attachment = new EmailAttachment();
                attachment.setURL(new URL(attachmentUrl));
                attachment.setDisposition(EmailAttachment.ATTACHMENT);
                attachment.setName("Attachment");
                ((MultiPartEmail) email).attach(attachment);
            } catch (MalformedURLException e) {
                logger.error("Invalid attachment url.", e);
            } catch (EmailException e) {
                logger.error("Error adding attachment to email.", e);
            }
        }

        email.setHostName(hostname);
        email.setSmtpPort(port);
        email.setTLS(tls);

        if (StringUtils.isNotBlank(username)) {
            if (popBeforeSmtp) {
                email.setPopBeforeSmtp(true, hostname, username, password);
            } else {
                email.setAuthenticator(new DefaultAuthenticator(username, password));
            }
        }

        try {
            email.setFrom(from);
            email.addTo(to);
            if (!StringUtils.isEmpty(subject))
                email.setSubject(subject);
            if (!StringUtils.isEmpty(message))
                email.setMsg(message);
            email.send();
            logger.debug("Sent email to '{}' with subject '{}'.", to, subject);
            success = true;
        } catch (EmailException e) {
            logger.error("Could not send e-mail to '" + to + ".", e);
        }
    } else {
        logger.error(
                "Cannot send e-mail because of missing configuration settings. The current settings are: "
                        + "Host: '{}', port '{}', from '{}', useTLS: {}, username: '{}', password '{}'",
                new String[] { hostname, String.valueOf(port), from, String.valueOf(tls), username, password });
    }

    return success;
}