Search in sources :

Example 6 with Email

use of org.apache.commons.mail.Email in project japid42 by branaway.

the class JapidMailer method send.

@SuppressWarnings("unchecked")
public static Future<Boolean> send(Object... args) {
    try {
        final HashMap<String, Object> infoMap = getInfoMap();
        // Body character set
        final String charset = (String) infoMap.get(CHARSET);
        // Headers
        final Map<String, String> headers = (Map<String, String>) infoMap.get(HEADERS);
        // Subject
        final String subject = (String) infoMap.get(SUBJECT);
        // xxx how to determine the method name???
        //            String templateName = (String) infoMap.get(METHOD);
        String templateNameBase = StackTraceUtils.getCaller();
        if (!templateNameBase.startsWith("notifiers")) {
            throw new RuntimeException("The emailers must be put in the \"notifiers\" package.");
        }
        //            if (templateNameBase.startsWith(NOTIFIERS)) {
        //                templateNameBase = templateNameBase.substring(NOTIFIERS.length());
        //            }
        //            if (templateNameBase.startsWith(CONTROLLERS)) {
        //                templateNameBase = templateNameBase.substring(CONTROLLERS.length());
        //            }
        //            templateNameBase = templateNameBase.substring(0, templateNameBase.indexOf("("));
        //            templateNameBase = templateNameBase.replace(".", "/");
        //            final Map<String, Object> templateHtmlBinding = new HashMap<String, Object>();
        //            final Map<String, Object> templateTextBinding = new HashMap<String, Object>();
        //            for (Object o : args) {
        //                List<String> names = LocalVariablesNamesTracer.getAllLocalVariableNames(o);
        //                for (String name : names) {
        //                    templateHtmlBinding.put(name, o);
        //                    templateTextBinding.put(name, o);
        //                }
        //            }
        String templateClassName = "japidviews._" + templateNameBase;
        String bodyHtml = null;
        Class tClass = JapidRenderer.getClass(templateClassName);
        if (tClass == null) {
            String templateFileName = templateClassName.replace('.', '/') + ".html";
            throw new RuntimeException("Japid Emailer: could not find a Japid template with the name of: " + templateFileName);
        } else if (JapidTemplateBase.class.isAssignableFrom(tClass)) {
            JapidResult jr = JapidController.render(tClass, args);
            RenderResult rr = jr.getRenderResult();
            bodyHtml = rr.getContent().toString();
        } else {
            throw new RuntimeException("The found class is not a Japid template class: " + templateClassName);
        }
        //    		System.out.println("email body: " + bodyHtml);
        // The rule is as follow: If we ask for text/plain, we don't care about the HTML
        // If we ask for HTML and there is a text/plain we add it as an alternative.
        // If contentType is not specified look at the template available:
        // - .txt only -> text/plain
        // else
        // -           -> text/html
        //            String contentType = (String) infoMap.get(CONTENT_TYPE);
        //            String bodyText = "";
        //            try {
        //                Template templateHtml = TemplateLoader.load(templateNameBase + ".html");
        //                bodyHtml = templateHtml.render(templateHtmlBinding);
        //            } catch (TemplateNotFoundException e) {
        //                if (contentType != null && !contentType.startsWith(TEXT_PLAIN)) {
        //                    throw e;
        //                }
        //            }
        ////
        //            try {
        //                Template templateText = TemplateLoader.load(templateName + ".txt");
        //                bodyText = templateText.render(templateTextBinding);
        //            } catch (TemplateNotFoundException e) {
        //                if (bodyHtml == null && (contentType == null || contentType.startsWith(TEXT_PLAIN))) {
        //                    throw e;
        //                }
        //            }
        // Content type
        // bran html for now
        //            if (contentType == null) {
        //                if (bodyHtml != null) {
        //                    contentType = TEXT_HTML;
        //                } else {
        //                    contentType = TEXT_PLAIN;
        //                }
        //            }
        // Recipients
        final List<Object> recipientList = (List<Object>) infoMap.get(RECIPIENTS);
        // From
        final Object from = infoMap.get(FROM);
        final Object replyTo = infoMap.get(REPLY_TO);
        Email email = null;
        if (infoMap.get(ATTACHMENTS) == null) {
            //                if (StringUtils.isEmpty(bodyHtml)) {
            //                    email = new SimpleEmail();
            //                    email.setMsg(bodyText);
            //                } else {
            HtmlEmail htmlEmail = new HtmlEmail();
            htmlEmail.setHtmlMsg(bodyHtml);
            //                    if (!StringUtils.isEmpty(bodyText)) {
            //                        htmlEmail.setTextMsg(bodyText);
            //                    }
            email = htmlEmail;
        //                }
        } else {
            //                if (StringUtils.isEmpty(bodyHtml)) {
            //                    email = new MultiPartEmail();
            //                    email.setMsg(bodyText);
            //                } else {
            HtmlEmail htmlEmail = new HtmlEmail();
            htmlEmail.setHtmlMsg(bodyHtml);
            //                    if (!StringUtils.isEmpty(bodyText)) {
            //                        htmlEmail.setTextMsg(bodyText);
            //                    }
            email = htmlEmail;
            //                }
            MultiPartEmail multiPartEmail = (MultiPartEmail) email;
            List<EmailAttachment> objectList = (List<EmailAttachment>) infoMap.get(ATTACHMENTS);
            for (EmailAttachment object : objectList) {
                multiPartEmail.attach(object);
            }
        }
        if (from != null) {
            try {
                InternetAddress iAddress = new InternetAddress(from.toString());
                email.setFrom(iAddress.getAddress(), iAddress.getPersonal());
            } catch (Exception e) {
                email.setFrom(from.toString());
            }
        }
        if (replyTo != null) {
            try {
                InternetAddress iAddress = new InternetAddress(replyTo.toString());
                email.addReplyTo(iAddress.getAddress(), iAddress.getPersonal());
            } catch (Exception e) {
                email.addReplyTo(replyTo.toString());
            }
        }
        if (recipientList != null) {
            for (Object recipient : recipientList) {
                try {
                    InternetAddress iAddress = new InternetAddress(recipient.toString());
                    email.addTo(iAddress.getAddress(), iAddress.getPersonal());
                } catch (Exception e) {
                    email.addTo(recipient.toString());
                }
            }
        } else {
            throw new PlayException("JapidMailer", "You must specify at least one recipient.", null);
        }
        List<Object> ccsList = (List<Object>) infoMap.get(CCS);
        if (ccsList != null) {
            for (Object cc : ccsList) {
                email.addCc(cc.toString());
            }
        }
        List<Object> bccsList = (List<Object>) infoMap.get(BCCS);
        if (bccsList != null) {
            for (Object bcc : bccsList) {
                try {
                    InternetAddress iAddress = new InternetAddress(bcc.toString());
                    email.addBcc(iAddress.getAddress(), iAddress.getPersonal());
                } catch (Exception e) {
                    email.addBcc(bcc.toString());
                }
            }
        }
        if (!StringUtils.isEmpty(charset)) {
            email.setCharset(charset);
        }
        email.setSubject(subject);
        email.updateContentType(TEXT_HTML);
        if (headers != null) {
            for (String key : headers.keySet()) {
                email.addHeader(key, headers.get(key));
            }
        }
        // reset the infomap
        infos.remove();
        return Mail.send(email);
    } catch (EmailException ex) {
        throw new MailException("Cannot send email", ex);
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Email(org.apache.commons.mail.Email) HtmlEmail(org.apache.commons.mail.HtmlEmail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) EmailAttachment(org.apache.commons.mail.EmailAttachment) RenderResult(cn.bran.japid.template.RenderResult) HtmlEmail(org.apache.commons.mail.HtmlEmail) UnexpectedException(play.api.UnexpectedException) MailException(cn.bran.play.exceptions.MailException) PlayException(play.api.PlayException) ExecutionException(java.util.concurrent.ExecutionException) EmailException(org.apache.commons.mail.EmailException) PlayException(play.api.PlayException) EmailException(org.apache.commons.mail.EmailException) ArrayList(java.util.ArrayList) List(java.util.List) MailException(cn.bran.play.exceptions.MailException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with Email

use of org.apache.commons.mail.Email in project graylog2-server by Graylog2.

the class FormattedEmailAlertSender method sendEmail.

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!");
    }
    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();
}
Also used : Email(org.apache.commons.mail.Email) SimpleEmail(org.apache.commons.mail.SimpleEmail) TransportConfigurationException(org.graylog2.plugin.alarms.transports.TransportConfigurationException) DefaultAuthenticator(org.apache.commons.mail.DefaultAuthenticator) SimpleEmail(org.apache.commons.mail.SimpleEmail)

Example 8 with Email

use of org.apache.commons.mail.Email in project SpringStepByStep by JavaProgrammerLB.

the class JavaMailDemo method sendSimpleTextMail.

//	@Test
public void sendSimpleTextMail() {
    try {
        Email email = new SimpleEmail();
        email.setHostName("smtp.googlemail.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator("username", "password"));
        email.setSSLOnConnect(true);
        email.setFrom("username");
        email.setSubject("TestMail");
        email.setMsg("This is a test mail ... :-)");
        email.addTo("foo@bar.com");
        email.send();
    } catch (EmailException e) {
        e.printStackTrace();
    }
}
Also used : Email(org.apache.commons.mail.Email) SimpleEmail(org.apache.commons.mail.SimpleEmail) ImageHtmlEmail(org.apache.commons.mail.ImageHtmlEmail) HtmlEmail(org.apache.commons.mail.HtmlEmail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) EmailException(org.apache.commons.mail.EmailException) DefaultAuthenticator(org.apache.commons.mail.DefaultAuthenticator) SimpleEmail(org.apache.commons.mail.SimpleEmail)

Example 9 with Email

use of org.apache.commons.mail.Email in project sling by apache.

the class SimpleMailBuilderIT method testBuildWithDefaults.

@Test
public void testBuildWithDefaults() throws Exception {
    final MailBuilder mailBuilder = getService(MailBuilder.class);
    final Email email = mailBuilder.build("Stop your messing around, Better think of your future...", "rudy@ghosttown", Collections.emptyMap());
    email.buildMimeMessage();
    final byte[] bytes = MailUtil.toByteArray(email);
    final String mail = new String(bytes, StandardCharsets.UTF_8);
    logger.debug("mail: " + mail);
    assertEquals("rudy@ghosttown", email.getToAddresses().get(0).getAddress());
    assertEquals("Rudy, A Message to You", email.getSubject());
    assertEquals("dandy.livingstone@kingston.jamaica", email.getFromAddress().getAddress());
    assertEquals("localhost", email.getHostName());
    logger.debug(email.getMimeMessage().getContent().toString());
}
Also used : Email(org.apache.commons.mail.Email) MailBuilder(org.apache.sling.commons.messaging.mail.MailBuilder) Test(org.junit.Test)

Example 10 with Email

use of org.apache.commons.mail.Email in project sling by apache.

the class SimpleMailBuilderIT method testBuildWithData.

@Test
public void testBuildWithData() throws Exception {
    final MailBuilder mailBuilder = getService(MailBuilder.class);
    final Map<String, String> configuration = new HashMap<>();
    configuration.put("mail.subject", "Rudy, A Message to You");
    configuration.put("mail.from", "specials@thespecials.com");
    final Map data = Collections.singletonMap("mail", configuration);
    final Email email = mailBuilder.build("A Message to You, Rudy", "rudy@ghosttown", data);
    email.buildMimeMessage();
    final byte[] bytes = MailUtil.toByteArray(email);
    final String mail = new String(bytes, StandardCharsets.UTF_8);
    logger.debug("mail: " + mail);
    assertEquals("rudy@ghosttown", email.getToAddresses().get(0).getAddress());
    assertEquals("Rudy, A Message to You", email.getSubject());
    assertEquals("specials@thespecials.com", email.getFromAddress().getAddress());
    assertEquals("localhost", email.getHostName());
    logger.debug(email.getMimeMessage().getContent().toString());
}
Also used : Email(org.apache.commons.mail.Email) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map) MailBuilder(org.apache.sling.commons.messaging.mail.MailBuilder) Test(org.junit.Test)

Aggregations

Email (org.apache.commons.mail.Email)11 EmailException (org.apache.commons.mail.EmailException)7 MultiPartEmail (org.apache.commons.mail.MultiPartEmail)6 Map (java.util.Map)5 HtmlEmail (org.apache.commons.mail.HtmlEmail)5 SimpleEmail (org.apache.commons.mail.SimpleEmail)5 HashMap (java.util.HashMap)4 EmailAttachment (org.apache.commons.mail.EmailAttachment)4 RenderResult (cn.bran.japid.template.RenderResult)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 ExecutionException (java.util.concurrent.ExecutionException)3 InternetAddress (javax.mail.internet.InternetAddress)3 DefaultAuthenticator (org.apache.commons.mail.DefaultAuthenticator)3 MailBuilder (org.apache.sling.commons.messaging.mail.MailBuilder)2 Test (org.junit.Test)2 MailException (play.exceptions.MailException)2 UnexpectedException (play.exceptions.UnexpectedException)2 MailException (cn.bran.play.exceptions.MailException)1 File (java.io.File)1