Search in sources :

Example 1 with MailTemplate

use of com.day.cq.commons.mail.MailTemplate in project acs-aem-commons by Adobe-Consulting-Services.

the class SMTPMailServiceHealthCheck method execute.

@Override
@SuppressWarnings("squid:S1141")
public Result execute() {
    final FormattingResultLog resultLog = new FormattingResultLog();
    if (messageGatewayService == null) {
        resultLog.critical("MessageGatewayService OSGi service could not be found.");
        resultLog.info("Verify the Default Mail Service is active: http://<host>:<port>/system/console/components/com.day.cq.mailer.impl.CqMailingService");
    } else {
        final MessageGateway<SimpleEmail> messageGateway = messageGatewayService.getGateway(SimpleEmail.class);
        if (messageGateway == null) {
            resultLog.critical("The AEM Default Mail Service is INACTIVE, thus e-mails cannot be sent.");
            resultLog.info("Verify the Default Mail Service is active and configured: http://<host>:<port>/system/console/components/com.day.cq.mailer.DefaultMailService");
            log.warn("Could not retrieve a SimpleEmail Message Gateway");
        } else {
            try {
                List<InternetAddress> emailAddresses = new ArrayList<InternetAddress>();
                emailAddresses.add(new InternetAddress(this.toEmail));
                MailTemplate mailTemplate = new MailTemplate(IOUtils.toInputStream(MAIL_TEMPLATE), CharEncoding.UTF_8);
                SimpleEmail email = mailTemplate.getEmail(StrLookup.mapLookup(Collections.emptyMap()), SimpleEmail.class);
                email.setSubject("AEM E-mail Service Health Check");
                email.setTo(emailAddresses);
                email.setSocketConnectionTimeout(TIMEOUT);
                email.setSocketTimeout(TIMEOUT);
                try {
                    messageGateway.send(email);
                    resultLog.info("The E-mail Service appears to be working properly. Verify the health check e-mail was sent to [ {} ]", this.toEmail);
                } catch (Exception e) {
                    resultLog.critical("Failed sending e-mail. Unable to send a test toEmail via the configured E-mail server: " + e.getMessage(), e);
                    log.warn("Failed to send E-mail for E-mail Service health check", e);
                }
                logMailServiceConfig(resultLog, email);
            } catch (Exception e) {
                resultLog.healthCheckError("Sling Health check could not formulate a test toEmail: " + e.getMessage(), e);
                log.error("Unable to execute E-mail health check", e);
            }
        }
    }
    return new Result(resultLog);
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) FormattingResultLog(org.apache.sling.hc.util.FormattingResultLog) ArrayList(java.util.ArrayList) MailTemplate(com.day.cq.commons.mail.MailTemplate) SimpleEmail(org.apache.commons.mail.SimpleEmail) Result(org.apache.sling.hc.api.Result)

Example 2 with MailTemplate

use of com.day.cq.commons.mail.MailTemplate in project acs-aem-commons by Adobe-Consulting-Services.

the class EmailServiceImpl method sendEmail.

@Override
public List<InternetAddress> sendEmail(final String templatePath, final Map<String, String> emailParams, final InternetAddress... recipients) {
    List<InternetAddress> failureList = new ArrayList<InternetAddress>();
    if (recipients == null || recipients.length <= 0) {
        throw new IllegalArgumentException(MSG_INVALID_RECIPIENTS);
    }
    final MailTemplate mailTemplate = this.getMailTemplate(templatePath);
    final Class<? extends Email> mailType = this.getMailType(templatePath);
    final MessageGateway<Email> messageGateway = messageGatewayService.getGateway(mailType);
    for (final InternetAddress address : recipients) {
        try {
            // Get a new email per recipient to avoid duplicate attachments
            final Email email = getEmail(mailTemplate, mailType, emailParams);
            email.setTo(Collections.singleton(address));
            messageGateway.send(email);
        } catch (Exception e) {
            failureList.add(address);
            log.error("Error sending email to [ " + address + " ]", e);
        }
    }
    return failureList;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Email(org.apache.commons.mail.Email) HtmlEmail(org.apache.commons.mail.HtmlEmail) SimpleEmail(org.apache.commons.mail.SimpleEmail) ArrayList(java.util.ArrayList) MailTemplate(com.day.cq.commons.mail.MailTemplate) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) IOException(java.io.IOException) LoginException(org.apache.sling.api.resource.LoginException) EmailException(org.apache.commons.mail.EmailException)

Example 3 with MailTemplate

use of com.day.cq.commons.mail.MailTemplate in project acs-aem-commons by Adobe-Consulting-Services.

the class EmailServiceImplTest method setUp.

@Before
public final void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    when(messageGatewayService.getGateway(SimpleEmail.class)).thenReturn(messageGatewaySimpleEmail);
    when(messageGatewayService.getGateway(HtmlEmail.class)).thenReturn(messageGatewayHtmlEmail);
    when(resourceResolverFactory.getServiceResourceResolver(Matchers.anyMap())).thenReturn(resourceResolver);
    when(resourceResolver.adaptTo(Session.class)).thenReturn(session);
    emailTemplatePath = new File(this.getClass().getResource("/emailTemplate.txt").toURI()).getPath();
    emailTemplateAttachmentPath = new File(this.getClass().getResource("/emailTemplateAttachment.html").toURI()).getPath();
    // Mock the Mail Template
    PowerMockito.mockStatic(MailTemplate.class);
    when(MailTemplate.create(emailTemplatePath, session)).thenReturn(new MailTemplate(new FileInputStream(emailTemplatePath), "UTF-8"));
    when(MailTemplate.create(emailTemplateAttachmentPath, session)).thenReturn(new MailTemplate(new FileInputStream(emailTemplateAttachmentPath), "UTF-8"));
}
Also used : MailTemplate(com.day.cq.commons.mail.MailTemplate) File(java.io.File) FileInputStream(java.io.FileInputStream) Before(org.junit.Before)

Example 4 with MailTemplate

use of com.day.cq.commons.mail.MailTemplate in project acs-aem-commons by Adobe-Consulting-Services.

the class EmailServiceImpl method sendEmail.

@Override
public List<InternetAddress> sendEmail(String templatePath, Map<String, String> emailParams, Map<String, DataSource> attachments, InternetAddress... recipients) {
    List<InternetAddress> failureList = new ArrayList<InternetAddress>();
    if (recipients == null || recipients.length <= 0) {
        throw new IllegalArgumentException(MSG_INVALID_RECIPIENTS);
    }
    final MailTemplate mailTemplate = this.getMailTemplate(templatePath);
    final Class<? extends Email> mailType;
    if (attachments != null && attachments.size() > 0) {
        mailType = HtmlEmail.class;
    } else {
        mailType = this.getMailType(templatePath);
    }
    final MessageGateway<Email> messageGateway = messageGatewayService.getGateway(mailType);
    for (final InternetAddress address : recipients) {
        try {
            // Get a new email per recipient to avoid duplicate attachments
            Email email = getEmail(mailTemplate, mailType, emailParams);
            email.setTo(Collections.singleton(address));
            if (attachments != null && attachments.size() > 0) {
                for (Map.Entry<String, DataSource> entry : attachments.entrySet()) {
                    ((HtmlEmail) email).attach(entry.getValue(), entry.getKey(), null);
                }
            }
            messageGateway.send(email);
        } catch (Exception e) {
            failureList.add(address);
            log.error("Error sending email to [ " + address + " ]", e);
        }
    }
    return failureList;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Email(org.apache.commons.mail.Email) HtmlEmail(org.apache.commons.mail.HtmlEmail) SimpleEmail(org.apache.commons.mail.SimpleEmail) ArrayList(java.util.ArrayList) HtmlEmail(org.apache.commons.mail.HtmlEmail) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) IOException(java.io.IOException) LoginException(org.apache.sling.api.resource.LoginException) EmailException(org.apache.commons.mail.EmailException) DataSource(javax.activation.DataSource) MailTemplate(com.day.cq.commons.mail.MailTemplate) Map(java.util.Map)

Example 5 with MailTemplate

use of com.day.cq.commons.mail.MailTemplate in project acs-aem-commons by Adobe-Consulting-Services.

the class EmailServiceImpl method getMailTemplate.

private MailTemplate getMailTemplate(String templatePath) throws IllegalArgumentException {
    MailTemplate mailTemplate = null;
    ResourceResolver resourceResolver = null;
    try {
        Map<String, Object> authInfo = Collections.singletonMap(ResourceResolverFactory.SUBSERVICE, (Object) SERVICE_NAME);
        resourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo);
        mailTemplate = MailTemplate.create(templatePath, resourceResolver.adaptTo(Session.class));
        if (mailTemplate == null) {
            throw new IllegalArgumentException("Mail template path [ " + templatePath + " ] could not resolve to a valid template");
        }
    } catch (LoginException e) {
        log.error("Unable to obtain an administrative resource resolver to get the Mail Template at [ " + templatePath + " ]", e);
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
    return mailTemplate;
}
Also used : MailTemplate(com.day.cq.commons.mail.MailTemplate) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) LoginException(org.apache.sling.api.resource.LoginException)

Aggregations

MailTemplate (com.day.cq.commons.mail.MailTemplate)5 ArrayList (java.util.ArrayList)3 InternetAddress (javax.mail.internet.InternetAddress)3 SimpleEmail (org.apache.commons.mail.SimpleEmail)3 LoginException (org.apache.sling.api.resource.LoginException)3 IOException (java.io.IOException)2 MessagingException (javax.mail.MessagingException)2 AddressException (javax.mail.internet.AddressException)2 Email (org.apache.commons.mail.Email)2 EmailException (org.apache.commons.mail.EmailException)2 HtmlEmail (org.apache.commons.mail.HtmlEmail)2 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 Map (java.util.Map)1 DataSource (javax.activation.DataSource)1 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)1 Result (org.apache.sling.hc.api.Result)1 FormattingResultLog (org.apache.sling.hc.util.FormattingResultLog)1 Before (org.junit.Before)1