Search in sources :

Example 1 with Email

use of org.apache.commons.mail.Email in project openhab1-addons by openhab.

the class Mail method sendMail.

/**
     * Sends an email with attachment(s) via SMTP
     *
     * @param to the email address of the recipient
     * @param subject the subject of the email
     * @param message the body of the email
     * @param attachmentUrlList a list of URL strings of the contents to send as attachments
     *
     * @return <code>true</code>, if sending the email has been successful and
     *         <code>false</code> in all other cases.
     */
@ActionDoc(text = "Sends an email with attachment via SMTP")
public static boolean sendMail(@ParamDoc(name = "to") String to, @ParamDoc(name = "subject") String subject, @ParamDoc(name = "message") String message, @ParamDoc(name = "attachmentUrlList") List<String> attachmentUrlList) {
    boolean success = false;
    if (MailActionService.isProperlyConfigured) {
        Email email = new SimpleEmail();
        if (attachmentUrlList != null && !attachmentUrlList.isEmpty()) {
            email = new MultiPartEmail();
            for (String attachmentUrl : attachmentUrlList) {
                // Create the attachment
                try {
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setURL(new URL(attachmentUrl));
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    String fileName = attachmentUrl.replaceFirst(".*/([^/?]+).*", "$1");
                    attachment.setName(isNotBlank(fileName) ? fileName : "Attachment");
                    ((MultiPartEmail) email).attach(attachment);
                } catch (MalformedURLException e) {
                    logger.error("Invalid attachment url.", e);
                } catch (EmailException e) {
                    logger.error("Error adding attachment to email.", e);
                }
            }
        }
        email.setHostName(hostname);
        email.setSmtpPort(port);
        email.setStartTLSEnabled(startTLSEnabled);
        email.setSSLOnConnect(sslOnConnect);
        if (isNotBlank(username)) {
            if (popBeforeSmtp) {
                email.setPopBeforeSmtp(true, hostname, username, password);
            } else {
                email.setAuthenticator(new DefaultAuthenticator(username, password));
            }
        }
        try {
            if (isNotBlank(charset)) {
                email.setCharset(charset);
            }
            email.setFrom(from);
            String[] toList = to.split(";");
            for (String toAddress : toList) {
                email.addTo(toAddress);
            }
            if (!isEmpty(subject)) {
                email.setSubject(subject);
            }
            if (!isEmpty(message)) {
                email.setMsg(message);
            }
            email.send();
            logger.debug("Sent email to '{}' with subject '{}'.", to, subject);
            success = true;
        } catch (EmailException e) {
            logger.error("Could not send e-mail to '" + to + "'.", e);
        }
    } else {
        logger.error("Cannot send e-mail because of missing configuration settings. The current settings are: " + "Host: '{}', port '{}', from '{}', startTLSEnabled: {}, sslOnConnect: {}, username: '{}', password '{}'", new Object[] { hostname, String.valueOf(port), from, String.valueOf(startTLSEnabled), String.valueOf(sslOnConnect), username, password });
    }
    return success;
}
Also used : MalformedURLException(java.net.MalformedURLException) Email(org.apache.commons.mail.Email) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) SimpleEmail(org.apache.commons.mail.SimpleEmail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) EmailAttachment(org.apache.commons.mail.EmailAttachment) EmailException(org.apache.commons.mail.EmailException) DefaultAuthenticator(org.apache.commons.mail.DefaultAuthenticator) SimpleEmail(org.apache.commons.mail.SimpleEmail) URL(java.net.URL) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 2 with Email

use of org.apache.commons.mail.Email in project Japid 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 = DirUtil.JAPIDVIEWS_ROOT + "._" + templateNameBase;
        String bodyHtml = null;
        Class tClass = Play.classloader.getClassIgnoreCase(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)) {
            try {
                JapidController.render(tClass, args);
            } catch (JapidResult jr) {
                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 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)

Example 3 with Email

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

the class MailActivityBehavior method execute.

@Override
public void execute(ActivityExecution execution) {
    boolean doIgnoreException = Boolean.parseBoolean(getStringFromField(ignoreException, execution));
    String exceptionVariable = getStringFromField(exceptionVariableName, execution);
    Email email = null;
    try {
        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 (ActivitiException 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);
}
Also used : ActivitiException(org.activiti.engine.ActivitiException) Email(org.apache.commons.mail.Email) HtmlEmail(org.apache.commons.mail.HtmlEmail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) SimpleEmail(org.apache.commons.mail.SimpleEmail) EmailException(org.apache.commons.mail.EmailException) File(java.io.File) LinkedList(java.util.LinkedList) DataSource(javax.activation.DataSource)

Example 4 with Email

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

the class SimpleMailBuilder method build.

@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);
    email.setMsg(message);
    email.addTo(recipient);
    email.setSubject(subject);
    email.setFrom(from);
    email.setHostName(smtpHostname);
    email.setSmtpPort(smtpPort);
    email.setAuthentication(smtpUsername, smtpPassword);
    return email;
}
Also used : Email(org.apache.commons.mail.Email) SimpleEmail(org.apache.commons.mail.SimpleEmail) SimpleEmail(org.apache.commons.mail.SimpleEmail) Map(java.util.Map)

Example 5 with Email

use of org.apache.commons.mail.Email 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

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