Search in sources :

Example 16 with MultiPartEmail

use of org.apache.commons.mail.MultiPartEmail in project ninja by ninjaframework.

the class CommonsmailHelperImpl method createMultiPartEmailWithContent.

/**
 * Creates a MultiPartEmail. Selects the correct implementation
 * regarding html (MultiPartEmail) and/or txt content or both.
 *
 * Populates the mutlipart email accordingly with the txt / html content.
 */
@Override
public MultiPartEmail createMultiPartEmailWithContent(Mail mail) throws EmailException {
    MultiPartEmail multiPartEmail;
    if (mail.getBodyHtml() == null || mail.getBodyHtml().equals("")) {
        multiPartEmail = new MultiPartEmail();
        multiPartEmail.setMsg(mail.getBodyText());
    } else if (mail.getBodyText() == null || mail.getBodyText().equals("")) {
        multiPartEmail = new HtmlEmail().setHtmlMsg(mail.getBodyHtml());
    } else {
        multiPartEmail = new HtmlEmail().setHtmlMsg(mail.getBodyHtml()).setTextMsg(mail.getBodyText());
    }
    // and return the nicely configured mail:
    return multiPartEmail;
}
Also used : MultiPartEmail(org.apache.commons.mail.MultiPartEmail) HtmlEmail(org.apache.commons.mail.HtmlEmail)

Example 17 with MultiPartEmail

use of org.apache.commons.mail.MultiPartEmail in project ninja by ninjaframework.

the class CommonsMailHelperImplTest method testDoPopulateMultipartMailWithContent.

/**
 * Note:
 * - Setting of header parameters not (yet) tested as we cannot get back the headers set easily.
 *
 * @throws Exception
 */
@Test
public void testDoPopulateMultipartMailWithContent() throws Exception {
    Mail mail = MailImplTestHelper.getMailImplWithDemoContent();
    MultiPartEmail multiPartEmail = commonsmailHelper.createMultiPartEmailWithContent(mail);
    commonsmailHelper.doPopulateMultipartMailWithContent(multiPartEmail, mail);
    assertTrue(doConvertAdressesToInternetAddressList(multiPartEmail.getBccAddresses()).contains(new InternetAddress("bcc1@domain")));
    assertTrue(doConvertAdressesToInternetAddressList(multiPartEmail.getBccAddresses()).contains(new InternetAddress("bcc2@domain")));
    assertEquals("subject", multiPartEmail.getSubject());
    assertEquals(new InternetAddress("from1@domain"), multiPartEmail.getFromAddress());
    assertTrue(doConvertAdressesToInternetAddressList(multiPartEmail.getReplyToAddresses()).contains(new InternetAddress("replyTo1@domain")));
    assertTrue(doConvertAdressesToInternetAddressList(multiPartEmail.getReplyToAddresses()).contains(new InternetAddress("replyTo2@domain")));
    assertTrue(doConvertAdressesToInternetAddressList(multiPartEmail.getCcAddresses()).contains(new InternetAddress("cc1@domain")));
    assertTrue(doConvertAdressesToInternetAddressList(multiPartEmail.getCcAddresses()).contains(new InternetAddress("cc1@domain")));
    assertTrue(doConvertAdressesToInternetAddressList(multiPartEmail.getBccAddresses()).contains(new InternetAddress("bcc1@domain")));
    assertTrue(doConvertAdressesToInternetAddressList(multiPartEmail.getBccAddresses()).contains(new InternetAddress("bcc2@domain")));
    assertTrue(doConvertAdressesToInternetAddressList(multiPartEmail.getToAddresses()).contains(new InternetAddress("to1@domain")));
    assertTrue(doConvertAdressesToInternetAddressList(multiPartEmail.getToAddresses()).contains(new InternetAddress("to2@domain")));
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Mail(ninja.postoffice.Mail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) Test(org.junit.Test)

Example 18 with MultiPartEmail

use of org.apache.commons.mail.MultiPartEmail in project ninja by ninjaframework.

the class PostofficeCommonsmailImpl method send.

@Override
public void send(Mail mail) throws EmailException, AddressException {
    // create a correct multipart email based on html / txt content:
    MultiPartEmail multiPartEmail = commonsmailHelper.createMultiPartEmailWithContent(mail);
    // fill the from, to, bcc, css and all other fields:
    commonsmailHelper.doPopulateMultipartMailWithContent(multiPartEmail, mail);
    // set server parameters so we can send the MultiPartEmail:
    commonsmailHelper.doSetServerParameter(multiPartEmail, smtpHost, smtpPort, smtpSsl, smtpStartTLS, smtpStartTLSRequired, smtpUser, smtpPassword, smtpDebug);
    // And send it:
    multiPartEmail.send();
}
Also used : MultiPartEmail(org.apache.commons.mail.MultiPartEmail)

Example 19 with MultiPartEmail

use of org.apache.commons.mail.MultiPartEmail 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 20 with MultiPartEmail

use of org.apache.commons.mail.MultiPartEmail in project Japid by branaway.

the class JapidMailer2 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.");
        }
        String templateClassName = DirUtil.JAPIDVIEWS_ROOT + "._" + templateNameBase;
        String bodyHtml = null;
        // Play.classloader.getClassIgnoreCase(templateClassName);
        Class<? extends JapidTemplateBaseWithoutPlay> tClass = JapidPlayRenderer.getTemplateClass(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 {
            try {
                JapidController2.render(tClass, args);
            } catch (JapidResult jr) {
                RenderResult rr = jr.getRenderResult();
                bodyHtml = rr.getContent().toString();
            }
        }
        // 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 MailException("You must specify at least one recipient.");
        }
        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) MailException(play.exceptions.MailException) ExecutionException(java.util.concurrent.ExecutionException) UnexpectedException(play.exceptions.UnexpectedException) EmailException(org.apache.commons.mail.EmailException) EmailException(org.apache.commons.mail.EmailException) ArrayList(java.util.ArrayList) List(java.util.List) MailException(play.exceptions.MailException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

MultiPartEmail (org.apache.commons.mail.MultiPartEmail)22 EmailException (org.apache.commons.mail.EmailException)11 EmailAttachment (org.apache.commons.mail.EmailAttachment)9 HtmlEmail (org.apache.commons.mail.HtmlEmail)6 ArrayList (java.util.ArrayList)4 List (java.util.List)4 InternetAddress (javax.mail.internet.InternetAddress)4 Email (org.apache.commons.mail.Email)4 RenderResult (cn.bran.japid.template.RenderResult)3 IOException (java.io.IOException)3 URL (java.net.URL)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 ExecutionException (java.util.concurrent.ExecutionException)3 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)3 Mail (ninja.postoffice.Mail)3 Test (org.junit.Test)3 MessagingException (javax.mail.MessagingException)2 MimeMessage (javax.mail.internet.MimeMessage)2 MailException (cn.bran.play.exceptions.MailException)1