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.apache.fineract.infrastructure.core.service.GmailBackedPlatformEmailService.java

@Override
public void sendToUserAccount(final EmailDetail emailDetail, final String unencodedPassword) {
    final Email email = new SimpleEmail();
    final SMTPCredentialsData smtpCredentialsData = this.externalServicesReadPlatformService
            .getSMTPCredentials();//from  w  ww.ja va  2 s .  c  o  m
    final String authuserName = smtpCredentialsData.getUsername();

    final String authuser = smtpCredentialsData.getUsername();
    final String authpwd = smtpCredentialsData.getPassword();

    // Very Important, Don't use email.setAuthentication()
    email.setAuthenticator(new DefaultAuthenticator(authuser, authpwd));
    email.setDebug(false); // true if you want to debug
    email.setHostName(smtpCredentialsData.getHost());
    try {
        if (smtpCredentialsData.isUseTLS()) {
            email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
        }
        email.setFrom(authuser, authuserName);

        final StringBuilder subjectBuilder = new StringBuilder().append("Fineract Prototype Demo: ")
                .append(emailDetail.getContactName()).append(" user account creation.");

        email.setSubject(subjectBuilder.toString());

        final String sendToEmail = emailDetail.getAddress();

        final StringBuilder messageBuilder = new StringBuilder()
                .append("You are receiving this email as your email account: ").append(sendToEmail)
                .append(" has being used to create a user account for an organisation named [")
                .append(emailDetail.getOrganisationName()).append("] on Fineract Prototype Demo.")
                .append("You can login using the following credentials: username: ")
                .append(emailDetail.getUsername()).append(" password: ").append(unencodedPassword);

        email.setMsg(messageBuilder.toString());

        email.addTo(sendToEmail, emailDetail.getContactName());
        email.send();
    } catch (final EmailException e) {
        throw new PlatformEmailSendException(e);
    }
}

From source file:org.apache.kylin.common.util.MailService.java

/**
 * @param receivers/*w w w. j a v  a 2s .com*/
 * @param subject
 * @param content
 * @return true or false indicating whether the email was delivered successfully
 * @throws IOException
 */
public boolean sendMail(List<String> receivers, String subject, String content, boolean isHtmlMsg) {

    if (!enabled) {
        logger.info("Email service is disabled; this mail will not be delivered: " + subject);
        logger.info("To enable mail service, set 'kylin.job.notification-enabled=true' in kylin.properties");
        return false;
    }

    Email email = new HtmlEmail();
    email.setHostName(host);
    email.setStartTLSEnabled(starttlsEnabled);
    if (starttlsEnabled) {
        email.setSslSmtpPort(port);
    } else {
        email.setSmtpPort(Integer.valueOf(port));
    }

    if (username != null && username.trim().length() > 0) {
        email.setAuthentication(username, password);
    }

    //email.setDebug(true);
    try {
        for (String receiver : receivers) {
            email.addTo(receiver);
        }

        email.setFrom(sender);
        email.setSubject(subject);
        email.setCharset("UTF-8");
        if (isHtmlMsg) {
            ((HtmlEmail) email).setHtmlMsg(content);
        } else {
            ((HtmlEmail) email).setTextMsg(content);
        }
        email.send();
        email.getMailSession();

    } catch (EmailException e) {
        logger.error(e.getLocalizedMessage(), e);
        return false;
    }

    return true;
}

From source file:org.apache.nifi.processors.email.TestListenSMTP.java

@Test
public void validateSuccessfulInteraction() throws Exception, EmailException {
    int port = NetworkUtils.availablePort();

    TestRunner runner = TestRunners.newTestRunner(ListenSMTP.class);
    runner.setProperty(ListenSMTP.SMTP_PORT, String.valueOf(port));
    runner.setProperty(ListenSMTP.SMTP_MAXIMUM_CONNECTIONS, "3");
    runner.setProperty(ListenSMTP.SMTP_TIMEOUT, "10 seconds");

    runner.assertValid();/*from ww w .  j a v  a  2 s. co  m*/
    runner.run(5, false);
    final int numMessages = 5;
    CountDownLatch latch = new CountDownLatch(numMessages);

    this.executor.schedule(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < numMessages; i++) {
                try {
                    Email email = new SimpleEmail();
                    email.setHostName("localhost");
                    email.setSmtpPort(port);
                    email.setFrom("alice@nifi.apache.org");
                    email.setSubject("This is a test");
                    email.setMsg("MSG-" + i);
                    email.addTo("bob@nifi.apache.org");
                    email.send();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                } finally {
                    latch.countDown();
                }
            }
        }
    }, 1500, TimeUnit.MILLISECONDS);

    boolean complete = latch.await(5000, TimeUnit.MILLISECONDS);
    runner.shutdown();
    assertTrue(complete);
    runner.assertAllFlowFilesTransferred(ListenSMTP.REL_SUCCESS, numMessages);
}

From source file:org.apache.nifi.processors.email.TestListenSMTP.java

@Test
public void validateSuccessfulInteractionWithTls() throws Exception, EmailException {
    System.setProperty("mail.smtp.ssl.trust", "*");
    System.setProperty("javax.net.ssl.keyStore", "src/test/resources/localhost-ks.jks");
    System.setProperty("javax.net.ssl.keyStorePassword", "localtest");
    int port = NetworkUtils.availablePort();

    TestRunner runner = TestRunners.newTestRunner(ListenSMTP.class);
    runner.setProperty(ListenSMTP.SMTP_PORT, String.valueOf(port));
    runner.setProperty(ListenSMTP.SMTP_MAXIMUM_CONNECTIONS, "3");
    runner.setProperty(ListenSMTP.SMTP_TIMEOUT, "10 seconds");

    // Setup the SSL Context
    SSLContextService sslContextService = new StandardSSLContextService();
    runner.addControllerService("ssl-context", sslContextService);
    runner.setProperty(sslContextService, StandardSSLContextService.TRUSTSTORE,
            "src/test/resources/localhost-ts.jks");
    runner.setProperty(sslContextService, StandardSSLContextService.TRUSTSTORE_PASSWORD, "localtest");
    runner.setProperty(sslContextService, StandardSSLContextService.TRUSTSTORE_TYPE, "JKS");
    runner.setProperty(sslContextService, StandardSSLContextService.KEYSTORE,
            "src/test/resources/localhost-ks.jks");
    runner.setProperty(sslContextService, StandardSSLContextService.KEYSTORE_PASSWORD, "localtest");
    runner.setProperty(sslContextService, StandardSSLContextService.KEYSTORE_TYPE, "JKS");
    runner.enableControllerService(sslContextService);

    // and add the SSL context to the runner
    runner.setProperty(ListenSMTP.SSL_CONTEXT_SERVICE, "ssl-context");
    runner.setProperty(ListenSMTP.CLIENT_AUTH, SSLContextService.ClientAuth.NONE.name());
    runner.assertValid();//from   w  w  w.  j a  va 2  s .  c o  m

    int messageCount = 5;
    CountDownLatch latch = new CountDownLatch(messageCount);
    runner.run(messageCount, false);

    this.executor.schedule(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < messageCount; i++) {
                try {
                    Email email = new SimpleEmail();
                    email.setHostName("localhost");
                    email.setSmtpPort(port);
                    email.setFrom("alice@nifi.apache.org");
                    email.setSubject("This is a test");
                    email.setMsg("MSG-" + i);
                    email.addTo("bob@nifi.apache.org");

                    // Enable STARTTLS but ignore the cert
                    email.setStartTLSEnabled(true);
                    email.setStartTLSRequired(true);
                    email.setSSLCheckServerIdentity(false);
                    email.send();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                } finally {
                    latch.countDown();
                }
            }
        }
    }, 1500, TimeUnit.MILLISECONDS);

    boolean complete = latch.await(5000, TimeUnit.MILLISECONDS);
    runner.shutdown();
    assertTrue(complete);
    runner.assertAllFlowFilesTransferred("success", messageCount);
}

From source file:org.apache.nifi.processors.email.TestListenSMTP.java

@Test
public void validateTooLargeMessage() throws Exception, EmailException {
    int port = NetworkUtils.availablePort();

    TestRunner runner = TestRunners.newTestRunner(ListenSMTP.class);
    runner.setProperty(ListenSMTP.SMTP_PORT, String.valueOf(port));
    runner.setProperty(ListenSMTP.SMTP_MAXIMUM_CONNECTIONS, "3");
    runner.setProperty(ListenSMTP.SMTP_TIMEOUT, "10 seconds");
    runner.setProperty(ListenSMTP.SMTP_MAXIMUM_MSG_SIZE, "10 B");

    runner.assertValid();// www. j a v  a2  s.com

    int messageCount = 1;
    CountDownLatch latch = new CountDownLatch(messageCount);

    runner.run(messageCount, false);

    this.executor.schedule(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < messageCount; i++) {
                try {
                    Email email = new SimpleEmail();
                    email.setHostName("localhost");
                    email.setSmtpPort(port);
                    email.setFrom("alice@nifi.apache.org");
                    email.setSubject("This is a test");
                    email.setMsg("MSG-" + i);
                    email.addTo("bob@nifi.apache.org");
                    email.send();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                } finally {
                    latch.countDown();
                }
            }
        }
    }, 1000, TimeUnit.MILLISECONDS);

    boolean complete = latch.await(5000, TimeUnit.MILLISECONDS);
    runner.shutdown();
    assertTrue(complete);
    runner.assertAllFlowFilesTransferred("success", 0);
}

From source file:org.apache.sling.commons.messaging.mail.internal.SimpleMailService.java

private MailResult sendMail(final String message, final String recipient, final Map data,
        final MailBuilder mailBuilder) {
    try {// w  ww  .j  a  v  a  2  s  .  c  om
        final Email email = mailBuilder.build(message, recipient, data);
        final String messageId = email.send();
        logger.info("mail '{}' sent", messageId);
        final byte[] bytes = MailUtil.toByteArray(email);
        return new MailResult(bytes);
    } catch (EmailException | MessagingException | IOException e) {
        throw new CompletionException(e);
    }
}

From source file:org.apache.wookie.helpers.WidgetKeyManager.java

/**
 * Send email./*from w ww . ja  v  a 2  s . c  om*/
 * 
 * @param mailserver - the SMTP mail server address
 * @param from
 * @param to
 * @param message
 * @throws Exception
 */
private static void sendEmail(String mailserver, int port, String from, String to, String message,
        String username, String password) throws EmailException {
    Email email = new SimpleEmail();
    email.setDebug(false); // true if you want to debug
    email.setHostName(mailserver);
    if (username != null) {
        email.setAuthentication(username, password);
        email.getMailSession().getProperties().put("mail.smtp.starttls.enable", "true");
    }
    email.setFrom(from, "Wookie Server");
    email.setSubject("Wookie API Key");
    email.setMsg(message);
    email.addTo(to);
    email.send();
}

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

public void execute(ActivityExecution execution) {
    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 = getStringFromField(text, execution);
    String htmlStr = getStringFromField(html, execution);
    String charSetStr = getStringFromField(charset, execution);

    Email email = createEmail(textStr, htmlStr);

    addTo(email, toStr);//  w w w  . j ava2 s . co  m
    setFrom(email, fromStr);
    addCc(email, ccStr);
    addBcc(email, bccStr);
    setSubject(email, subjectStr);
    setMailServerProperties(email);
    setCharset(email, charSetStr);

    try {
        email.send();
    } catch (EmailException e) {
        throw new ProcessEngineException("Could not send e-mail", e);
    }
    leave(execution);
}

From source file:org.camunda.bpm.quickstart.TaskAssignmentListener.java

public void notify(DelegateTask delegateTask) {

    String assignee = delegateTask.getAssignee();
    String taskId = delegateTask.getId();

    if (assignee != null) {

        // Get User Profile from User Management
        IdentityService identityService = Context.getProcessEngineConfiguration().getIdentityService();
        User user = identityService.createUserQuery().userId(assignee).singleResult();

        if (user != null) {

            // Get Email Address from User Profile
            String recipient = user.getEmail();

            if (recipient != null && !recipient.isEmpty()) {

                Email email = new SimpleEmail();
                email.setCharset("utf-8");
                email.setHostName(HOST);
                email.setAuthentication(USER, PWD);

                try {
                    email.setFrom("noreply@camunda.org");
                    email.setSubject("Task assigned: " + delegateTask.getName());
                    email.setMsg("Please complete: http://localhost:8080/camunda/app/tasklist/default/#/task/"
                            + taskId);/*from  ww w. j av  a 2s .  c o  m*/

                    email.addTo(recipient);

                    email.send();
                    LOGGER.info("Task Assignment Email successfully sent to user '" + assignee
                            + "' with address '" + recipient + "'.");

                } catch (Exception e) {
                    LOGGER.log(Level.WARNING, "Could not send email to assignee", e);
                }

            } else {
                LOGGER.warning("Not sending email to user " + assignee + "', user has no email address.");
            }

        } else {
            LOGGER.warning(
                    "Not sending email to user " + assignee + "', user is not enrolled with identity service.");
        }

    }

}

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

/**
 * send an email./*from  w  w  w . j  a v  a  2 s.c o m*/
 */
public boolean sendEmail(Email email) {
    boolean sended = true;

    try {
        //         email.setHostName(smtpServer);
        //
        //         if (smtpUser != null && smtpUser.length() > 0)
        //            email.setAuthentication(smtpUser, smtpPassword);
        //
        //         email.setDebug(smtpDebug);
        //         email.setSmtpPort(smtpPort);
        //         email.setSSL(smtpSSL);
        //         email.setSslSmtpPort(String.valueOf(smtpSslPort));
        //         email.setTLS(smtpTLS);

        setEmailStandardData(email);

        email.send();
    } catch (EmailException e) {
        logger.error(e.getLocalizedMessage(), e);
        sended = false;
    }

    return sended;
}