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

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

Introduction

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

Prototype

public String send() throws EmailException 

Source Link

Document

Sends the email.

Usage

From source file:org.chenillekit.mail.services.impl.MailServiceImpl.java

/**
 * send a plain text message./*  www  .  j  a v a2  s.  co m*/
 *
 * @param headers    the mail headers
 * @param body      the mail body (text based)
 * @param dataSources array of data sources to attach at this mail
 *
 * @return true if mail successfull send
 */
public boolean sendPlainTextMail(MailMessageHeaders headers, String body, DataSource... dataSources) {
    try {
        Email email = new SimpleEmail();

        if (dataSources != null && dataSources.length > 0) {
            MultiPartEmail multiPart = new MultiPartEmail();

            for (DataSource dataSource : dataSources)
                multiPart.attach(dataSource, dataSource.getName(), dataSource.getName());

            email = multiPart;
        }

        setEmailStandardData(email);

        setMailMessageHeaders(email, headers);

        email.setCharset(headers.getCharset());
        try {
            email.setMsg(new String(body.getBytes(), headers.getCharset()));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        String msgId = email.send();

        return true;
    } catch (EmailException e) {
        // FIXME Handle gracefully
        throw new RuntimeException(e);
    }
}

From source file:org.cobbzilla.mail.sender.SmtpMailSender.java

protected void sendEmail_internal(Email email) throws EmailException {
    long wait = 5000;
    for (int tries = 0; tries < MAX_TRIES; tries++) {
        try {/*  w  w  w .  j  a v a2s.  c  o  m*/
            email.send();
            return;

        } catch (EmailException e) {
            if (tries < MAX_TRIES) {
                log.warn("Error sending email (try #" + (tries + 1) + ", will retry): " + e);
                sleep(wait, "waiting to send sending email (try #" + (tries + 1) + ", abandoning)");
                wait *= 2;

            } else {
                log.warn("Error sending email (try #" + tries + ", abandoning): " + e);
                throw e;
            }
        }
    }
}

From source file:org.dllearner.algorithms.qtl.experiments.PRConvergenceExperiment.java

private void sendFinishedMail() throws EmailException, IOException {
    Properties config = new Properties();
    config.load(Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("org/dllearner/algorithms/qtl/qtl-mail.properties"));

    Email email = new SimpleEmail();
    email.setHostName(config.getProperty("hostname"));
    email.setSmtpPort(465);/*from   ww  w . java 2  s.  com*/
    email.setAuthenticator(
            new DefaultAuthenticator(config.getProperty("username"), config.getProperty("password")));
    email.setSSLOnConnect(true);
    email.setFrom(config.getProperty("from"));
    email.setSubject("QTL evaluation finished.");
    email.setMsg("QTL evaluation finished.");
    email.addTo(config.getProperty("to"));
    email.send();
}

From source file:org.fao.geonet.util.MailUtil.java

private static Boolean send(final Email email) {
    try {//from  w w w  . ja v  a2  s  . c o  m
        email.send();

    } catch (EmailException e) {
        Log.error(LOG_MODULE_NAME, "Error sending email \"" + email.getSubject() + "\"", e);
        return false;
    }

    return true;
}

From source file:org.fao.geonet.util.MailUtil.java

private static void sendWithThread(@Nonnull final Email email) {
    try {/*from   ww w.  j  ava 2  s  . com*/
        Thread t = new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    email.send();
                } catch (EmailException e) {
                    Log.error(LOG_MODULE_NAME,
                            "Error sending email \"" + email.getSubject() + "\" unsing other " + "thread", e);
                }
            }
        };

        t.start();
    } catch (Exception e) {
        Log.error(LOG_MODULE_NAME,
                "Error sending email \"" + email.getSubject() + "\" unsing other " + "thread", e);
    }
}

From source file:org.fao.geonet.util.MailUtil.java

public static void testSendMail(List<String> toAddress, String subject, String message, String htmlMessage,
        SettingManager settings, String replyTo, String replyToDesc) throws Exception {
    // Create data information to compose the mail
    boolean isHtml = StringUtils.isNotBlank(htmlMessage);
    Email email = isHtml ? new HtmlEmail() : new SimpleEmail();
    configureBasics(settings, email);/* w ww  . j a  va 2s .  c  o m*/

    List<InternetAddress> addressColl = new ArrayList<InternetAddress>();

    addressColl.add(new InternetAddress(replyTo, replyToDesc));
    email.setReplyTo(addressColl);
    email.setSubject(subject);

    if (StringUtils.isNotBlank(message)) {
        email.setMsg(message);
    }
    if (isHtml) {
        ((HtmlEmail) email).setHtmlMsg(htmlMessage);
    }

    // send to all mails extracted from settings
    for (String add : toAddress) {
        email.addBcc(add);
    }

    email.send();
}

From source file:org.flowable.engine.impl.bpmn.behavior.MailActivityBehavior.java

@Override
public void execute(DelegateExecution execution) {

    boolean doIgnoreException = Boolean.parseBoolean(getStringFromField(ignoreException, execution));
    String exceptionVariable = getStringFromField(exceptionVariableName, execution);
    Email email = null;
    try {/*from   www.  j  av a2 s  . c  o  m*/
        String toStr = getStringFromField(to, execution);
        String fromStr = getStringFromField(from, execution);
        String ccStr = getStringFromField(cc, execution);
        String bccStr = getStringFromField(bcc, execution);
        String subjectStr = getStringFromField(subject, execution);
        String textStr = textVar == null ? getStringFromField(text, execution)
                : getStringFromField(getExpression(execution, textVar), execution);
        String htmlStr = htmlVar == null ? getStringFromField(html, execution)
                : getStringFromField(getExpression(execution, htmlVar), execution);
        String charSetStr = getStringFromField(charset, execution);
        List<File> files = new LinkedList<File>();
        List<DataSource> dataSources = new LinkedList<DataSource>();
        getFilesFromFields(attachments, execution, files, dataSources);

        email = createEmail(textStr, htmlStr, attachmentsExist(files, dataSources));
        addTo(email, toStr);
        setFrom(email, fromStr, execution.getTenantId());
        addCc(email, ccStr);
        addBcc(email, bccStr);
        setSubject(email, subjectStr);
        setMailServerProperties(email, execution.getTenantId());
        setCharset(email, charSetStr);
        attach(email, files, dataSources);

        email.send();

    } catch (FlowableException e) {
        handleException(execution, e.getMessage(), e, doIgnoreException, exceptionVariable);
    } catch (EmailException e) {
        handleException(execution, "Could not send e-mail in execution " + execution.getId(), e,
                doIgnoreException, exceptionVariable);
    }

    leave(execution);
}

From source file:org.graylog2.alerts.FormattedEmailAlertSender.java

private void sendEmail(String emailAddress, Stream stream, AlertCondition.CheckResult checkResult,
        List<Message> backlog) throws TransportConfigurationException, EmailException {
    LOG.debug("Sending mail to " + emailAddress);
    if (!configuration.isEnabled()) {
        throw new TransportConfigurationException(
                "Email transport is not enabled in server configuration file!");
    }/*from w ww .j  a  v  a2  s .c  o  m*/

    final Email email = new SimpleEmail();
    email.setCharset(EmailConstants.UTF_8);

    if (isNullOrEmpty(configuration.getHostname())) {
        throw new TransportConfigurationException(
                "No hostname configured for email transport while trying to send alert email!");
    } else {
        email.setHostName(configuration.getHostname());
    }
    email.setSmtpPort(configuration.getPort());
    if (configuration.isUseSsl()) {
        email.setSslSmtpPort(Integer.toString(configuration.getPort()));
    }

    if (configuration.isUseAuth()) {
        email.setAuthenticator(new DefaultAuthenticator(Strings.nullToEmpty(configuration.getUsername()),
                Strings.nullToEmpty(configuration.getPassword())));
    }

    email.setSSLOnConnect(configuration.isUseSsl());
    email.setStartTLSEnabled(configuration.isUseTls());
    if (pluginConfig != null && !isNullOrEmpty(pluginConfig.getString("sender"))) {
        email.setFrom(pluginConfig.getString("sender"));
    } else {
        email.setFrom(configuration.getFromEmail());
    }
    email.setSubject(buildSubject(stream, checkResult, backlog));
    email.setMsg(buildBody(stream, checkResult, backlog));
    email.addTo(emailAddress);

    email.send();
}

From source file:org.graylog2.alerts.StaticEmailAlertSender.java

private void sendEmail(String emailAddress, Stream stream, AlertCondition.CheckResult checkResult,
        List<Message> backlog) throws TransportConfigurationException, EmailException {
    LOG.debug("Sending mail to " + emailAddress);
    if (!configuration.isEnabled()) {
        throw new TransportConfigurationException(
                "Email transport is not enabled in server configuration file!");
    }/*from   w w  w  . jav  a2s  .c  om*/

    final Email email = new SimpleEmail();
    email.setCharset(EmailConstants.UTF_8);

    if (Strings.isNullOrEmpty(configuration.getHostname())) {
        throw new TransportConfigurationException(
                "No hostname configured for email transport while trying to send alert email!");
    } else {
        email.setHostName(configuration.getHostname());
    }
    email.setSmtpPort(configuration.getPort());
    if (configuration.isUseSsl()) {
        email.setSslSmtpPort(Integer.toString(configuration.getPort()));
    }

    if (configuration.isUseAuth()) {
        email.setAuthenticator(new DefaultAuthenticator(Strings.nullToEmpty(configuration.getUsername()),
                Strings.nullToEmpty(configuration.getPassword())));
    }

    email.setSSLOnConnect(configuration.isUseSsl());
    email.setStartTLSEnabled(configuration.isUseTls());
    if (pluginConfig != null && !Strings.isNullOrEmpty(pluginConfig.getString("sender"))) {
        email.setFrom(pluginConfig.getString("sender"));
    } else {
        email.setFrom(configuration.getFromEmail());
    }
    email.setSubject(buildSubject(stream, checkResult, backlog));
    email.setMsg(buildBody(stream, checkResult, backlog));
    email.addTo(emailAddress);

    email.send();
}

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

private void sendMail(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();//from w  w w  .  j  av  a2  s.c  om

    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);
}