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

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

Introduction

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

Prototype

public abstract Email setMsg(String msg) throws EmailException;

Source Link

Document

Define the content of the mail.

Usage

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();//w  ww  .  j av  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   ww w .  j  ava2s.com*/

    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();/*  ww w  . ja  va2  s  .  c o  m*/

    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.SimpleMailBuilder.java

@Override
public Email build(@Nonnull final String message, @Nonnull final String recipient, @Nonnull final Map data)
        throws EmailException {
    final Map configuration = (Map) data.getOrDefault("mail", Collections.EMPTY_MAP);
    final String subject = (String) configuration.getOrDefault(SUBJECT_KEY, this.configuration.subject());
    final String from = (String) configuration.getOrDefault(FROM_KEY, this.configuration.from());
    final String charset = (String) configuration.getOrDefault(CHARSET_KEY, this.configuration.charset());
    final String smtpHostname = (String) configuration.getOrDefault(SMTP_HOSTNAME_KEY,
            this.configuration.smtpHostname());
    final int smtpPort = (Integer) configuration.getOrDefault(SMTP_PORT_KEY, this.configuration.smtpPort());
    final String smtpUsername = (String) configuration.getOrDefault(SMTP_USERNAME_KEY,
            this.configuration.smtpUsername());
    final String smtpPassword = (String) configuration.getOrDefault(SMTP_PASSWORD_KEY,
            this.configuration.smtpPassword());

    final Email email = new SimpleEmail();
    email.setCharset(charset);/*from   w  w  w .j  a  v  a 2  s  .  c o  m*/
    email.setMsg(message);
    email.addTo(recipient);
    email.setSubject(subject);
    email.setFrom(from);
    email.setHostName(smtpHostname);
    email.setSmtpPort(smtpPort);
    email.setAuthentication(smtpUsername, smtpPassword);
    return email;
}

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

/**
 * Send email./*from  w ww  .  ja v a  2s . c o m*/
 * 
 * @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.example.coffee.service.SendMailTask.java

private void sendMail(String to) throws EmailException {
    String host = mailProperties.getProperty("host");
    Integer port = Integer.valueOf(mailProperties.getProperty("port"));
    String user = mailProperties.getProperty("user");
    String password = mailProperties.getProperty("password");

    String from = mailProperties.getProperty("from");

    Email email = new SimpleEmail();
    email.setHostName(host);/*  w  ww .  j  av  a  2 s .c  o m*/
    email.setTLS(true);
    email.setSmtpPort(port);
    email.setAuthentication(user, password);

    email.setFrom(from);
    email.setSubject("Your Coffee");
    email.setMsg("...is ready to drink.");
    email.addTo(to);

    getMailProvider().send(email);
}

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  w w w. j a v  a  2  s .  c om

                    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 a plain text message.// www .ja v  a 2  s . com
 *
 * @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

private Email constructEmail(SimpleEmailMessage message) throws EmailException {
    final Email email;
    if (message instanceof ICalEvent) {
        final MultiPartEmail multiPartEmail = new MultiPartEmail();

        ICalEvent iCalEvent = (ICalEvent) message;

        // Calendar iCalendar = new Calendar();
        Calendar iCalendar = ICalUtil.newCalendarEvent(iCalEvent.getProdId(), iCalEvent);
        byte[] attachmentData = ICalUtil.toBytes(iCalendar);

        String icsName = iCalEvent.getIcsName() + ".ics";
        String contentType = "text/calendar; icsName=\"" + icsName + "\"";
        try {//from   w w  w  . j a  va 2  s .  co m
            multiPartEmail.attach(new ByteArrayDataSource(attachmentData, contentType), icsName, "",
                    EmailAttachment.ATTACHMENT);
        } catch (IOException e) {
            throw new EmailException("constructEmail: couldn't attach: " + e, e);
        }
        email = multiPartEmail;

    } else if (message.getHasHtmlMessage()) {
        final HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setTextMsg(message.getMessage());
        htmlEmail.setHtmlMsg(message.getHtmlMessage());
        email = htmlEmail;

    } else {
        email = new SimpleEmail();
        email.setMsg(message.getMessage());
    }
    return email;
}

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);//w  w w  . j  a  va2  s .  c om
    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();
}