@Override
  public EmailTemplate generateSystemEmailTemplate(String name) {
    try {
      String templatePath = BASE_PATH + encodeTemplateName(name);
      File templateFile = new File(templatePath);

      String data = FileUtils.readFileToString(templateFile);

      // Remove any comment lines
      data = data.replaceAll("\\s*#.*[\\n\\r]{1}", "");

      // Extract the subject
      Matcher subjectMatcher = SUBJECT_PATTERN.matcher(data);
      if (!subjectMatcher.find())
        throw new IllegalStateException("Unable to identify the template's subject.");
      String subject = subjectMatcher.group(1).trim();

      // Trim the subject leaving just the body.
      int index = data.indexOf("\n");
      if (index < 0) index = data.indexOf("\r");
      String message = data.substring(index);

      if (subject == null || subject.length() == 0)
        throw new IllegalStateException("Unable to identify the template's subject.");

      if (message == null || message.length() == 0)
        throw new IllegalStateException("Unable to identify the template's message.");

      try {
        context.turnOffAuthorization();

        // Check if the template allready exists
        EmailTemplate template = settingRepo.findEmailTemplateByName(name);
        if (template == null) {
          // The template dosn't exist, so create a new one.
          template = settingRepo.createEmailTemplate(name, subject, message);
        } else {
          // The template allready exists. Update it's contents.
          template.setSubject(subject);
          template.setMessage(message);
        }
        template.setSystemRequired(true);

        template.save();
        return template;
      } finally {
        context.restoreAuthorization();
      }

    } catch (Exception e) {
      throw new IllegalStateException("Unable to generate system email template: " + name, e);
    }
  }
  @Override
  public List<EmailTemplate> generateAllSystemEmailTemplates() {

    List<EmailTemplate> created = new ArrayList<EmailTemplate>();
    for (String name : getAllSystemEmailTemplateNames()) {

      EmailTemplate template = settingRepo.findEmailTemplateByName(name);

      if (template == null) {
        template = generateSystemEmailTemplate(name);
        created.add(template);
      }
    }

    return created;
  }