Skip to content

Instantly share code, notes, and snippets.

@jdorrance
Last active December 18, 2015 04:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jdorrance/5729558 to your computer and use it in GitHub Desktop.
Save jdorrance/5729558 to your computer and use it in GitHub Desktop.
package org.mavendc.cq.test.workflow.impl
import org.apache.commons.lang.text.StrLookup
import org.apache.commons.mail.HtmlEmail
import org.apache.felix.scr.annotations.Component
import org.apache.felix.scr.annotations.Reference
import org.apache.felix.scr.annotations.Service
import org.apache.jackrabbit.api.security.user.Authorizable
import org.apache.jackrabbit.api.security.user.Group
import org.apache.sling.api.resource.Resource
import org.apache.sling.api.resource.ResourceResolverFactory
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.mavendc.cq.test.workflow.EmailUtils
import com.day.cq.commons.mail.MailTemplate
import com.day.cq.mailer.MessageGateway
import com.day.cq.mailer.MessageGatewayService
@Component
@Service
class EmailUtilsImpl implements EmailUtils {
@Reference
private MessageGatewayService messageGatewayService
@Reference
private ResourceResolverFactory resFactory;
private static Logger log = LoggerFactory.getLogger(EmailUtilsImpl.class);
@Override
public HtmlEmail getEmail(Map<String,String> params, String templatePath) {
def resolver = resFactory?.getAdministrativeResourceResolver(null)
Resource emailRes = resolver.getResource(templatePath)
MailTemplate temp = MailTemplate.create(emailRes.getPath(), emailRes.resourceResolver.adaptTo(javax.jcr.Session.class))
HtmlEmail email = temp.getEmail(StrLookup.mapLookup(params), HtmlEmail.class)
return email
}
@Override
public HtmlEmail addRecipients(HtmlEmail email, String[] recipients){
recipients.each(){ email.addTo(it) }
return email
}
@Override
public HtmlEmail addRecipients(HtmlEmail email, Authorizable[] authz){
authz.each(){Authorizable a ->
email = addRecipientsRecursively(email,a)
}
return email
}
@Override
public Boolean sendEmail(HtmlEmail email) {
try{
MessageGateway gateway = messageGatewayService.getGateway(HtmlEmail.class)
gateway.send(email)
return true;
}catch(Exception e){
log.error(e)
return false
}
}
private HtmlEmail addRecipientsRecursively(HtmlEmail em,Authorizable a){
if(a.isGroup()){
Group g = (Group)a
g.getDeclaredMembers().each(){ Authorizable ga ->
if(a.getID() != ga.getID()) addRecipientsRecursively(em,ga)
}
}
if(!a.isGroup() && a.hasProperty("profile/email")){
String emAd = a.getProperty("profile/email")[0].string
if(emAd && !emailContainsAddress(em,emAd))em.addTo(emAd)
}
return em
}
private boolean emailContainsAddress(HtmlEmail em, String addr){
if(em.toAddresses.toListString().contains(addr))return true
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment