Search in sources :

Example 36 with MailerResult

use of org.olat.core.util.mail.MailerResult in project OpenOLAT by OpenOLAT.

the class NotificationsManagerImpl method sendEmail.

private boolean sendEmail(Identity to, Translator translator, List<SubscriptionItem> subItems) {
    String title = translator.translate("rss.title", new String[] { NotificationHelper.getFormatedName(to) });
    StringBuilder htmlText = new StringBuilder();
    htmlText.append("<style>");
    htmlText.append(".o_m_sub h4 {margin: 0 0 10px 0;}");
    htmlText.append(".o_m_sub ul {padding: 0 0 5px 20px; margin: 0;}");
    htmlText.append(".o_m_sub ul li {padding: 0; margin: 1px 0;}");
    htmlText.append(".o_m_go {padding: 5px 0 0 0}");
    htmlText.append(".o_date {font-size: 90%; color: #888}");
    htmlText.append(".o_m_footer {background: #FAFAFA; border: 1px solid #eee; border-radius: 5px; padding: 0 0.5em 0.5em 0.5em; margin: 1em 0 1em 0;' class='o_m_h'}");
    htmlText.append("</style>");
    for (Iterator<SubscriptionItem> it_subs = subItems.iterator(); it_subs.hasNext(); ) {
        SubscriptionItem subitem = it_subs.next();
        // o_m_wrap class for overriding styles in master mail template
        htmlText.append("<div class='o_m_wrap'>");
        // add background here for gmail as they ignore classes.
        htmlText.append("<div class='o_m_sub' style='background: #FAFAFA; padding: 5px 5px; margin: 10px 0;'>");
        // 1: title
        htmlText.append(subitem.getTitle());
        htmlText.append("\n");
        // 2: content
        String desc = subitem.getDescription();
        if (StringHelper.containsNonWhitespace(desc)) {
            htmlText.append(desc);
        }
        // 3: goto-link
        String link = subitem.getLink();
        if (StringHelper.containsNonWhitespace(link)) {
            htmlText.append("<div class='o_m_go'><a href=\"").append(link).append("\">");
            SubscriptionInfo subscriptionInfo = subitem.getSubsInfo();
            if (subscriptionInfo != null) {
                String innerType = subscriptionInfo.getType();
                String typeName = NewControllerFactory.translateResourceableTypeName(innerType, translator.getLocale());
                String open = translator.translate("resource.open", new String[] { typeName });
                htmlText.append(open);
                htmlText.append(" &raquo;</a></div>");
            }
        }
        htmlText.append("\n");
        htmlText.append("</div></div>");
    }
    String basePath = Settings.getServerContextPathURI() + "/auth/HomeSite/" + to.getKey() + "/";
    htmlText.append("<div class='o_m_footer'>");
    htmlText.append(translator.translate("footer.notifications", new String[] { basePath + "mysettings/0", basePath += "notifications/0", basePath + "/tab/1" }));
    htmlText.append("</div>");
    MailerResult result = null;
    try {
        MailBundle bundle = new MailBundle();
        bundle.setToId(to);
        bundle.setContent(title, htmlText.toString());
        result = CoreSpringFactory.getImpl(MailManager.class).sendExternMessage(bundle, null, true);
    } catch (Exception e) {
    // FXOLAT-294 :: sending the mail will throw nullpointer exception if To-Identity has no
    // valid email-address!, catch it...
    }
    if (result == null || result.getReturnCode() > 0) {
        if (result != null)
            log.warn("Could not send email to identity " + to.getName() + ". (returncode=" + result.getReturnCode() + ", to=" + to + ")");
        else
            log.warn("Could not send email to identity " + to.getName() + ". (returncode = null) , to=" + to + ")");
        return false;
    } else {
        return true;
    }
}
Also used : SubscriptionItem(org.olat.core.commons.services.notifications.SubscriptionItem) MailerResult(org.olat.core.util.mail.MailerResult) SubscriptionInfo(org.olat.core.commons.services.notifications.SubscriptionInfo) NoSubscriptionInfo(org.olat.core.commons.services.notifications.model.NoSubscriptionInfo) MailBundle(org.olat.core.util.mail.MailBundle) AssertException(org.olat.core.logging.AssertException)

Example 37 with MailerResult

use of org.olat.core.util.mail.MailerResult in project OpenOLAT by OpenOLAT.

the class MailListController method event.

@Override
protected void event(UserRequest ureq, Controller source, Event event) {
    if (source == tableCtr) {
        if (event.getCommand().equals(Table.COMMANDLINK_ROWACTION_CLICKED)) {
            TableEvent te = (TableEvent) event;
            String actionid = te.getActionId();
            int rowid = te.getRowId();
            DBMailLight mail = (DBMailLight) tableCtr.getTableDataModel().getObject(rowid);
            if (CMD_READ.equals(actionid)) {
                if (outbox && StringHelper.containsNonWhitespace(mail.getMetaId()) && !mail.getMetaId().equals(metaId)) {
                    selectMetaMail(ureq, mail.getMetaId());
                } else {
                    selectMail(ureq, mail.getKey());
                }
            } else if (CMD_PROFILE.equals(actionid)) {
                DBMailRecipient from = mail.getFrom();
                if (from != null && from.getRecipient() != null) {
                    contextResolver.open(ureq, getWindowControl(), "[Identity:" + from.getRecipient().getKey() + "]");
                }
            } else if (CMD_MARK_TOGGLE.equals(actionid)) {
                mail = mailManager.toggleMarked(mail, getIdentity());
                replaceInModel(mail);
            } else if (CMD_READ_TOGGLE.equals(actionid)) {
                mail = mailManager.toggleRead(mail, getIdentity());
                replaceInModel(mail);
            }
        } else if (event.getCommand().equals(Table.COMMAND_MULTISELECT)) {
            // Multiselect events
            TableMultiSelectEvent tmse = (TableMultiSelectEvent) event;
            BitSet selectedMails = tmse.getSelection();
            if (selectedMails.isEmpty()) {
                tableVC.setDirty(true);
                showWarning("mail.action.emtpy");
                return;
            }
            String actionid = tmse.getAction();
            if (CMD_DELETE.equals(actionid)) {
                String title = translate("mail.confirm.delete.title");
                int selected = selectedMails.cardinality();
                String text;
                if (selected == 1) {
                    text = translate("mail.confirm.delete.single.text");
                } else {
                    text = translate("mail.confirm.delete.multi.text", selected + "");
                }
                deleteConfirmationBox = activateYesNoDialog(ureq, title, text, deleteConfirmationBox);
                deleteConfirmationBox.setUserObject(selectedMails);
            } else if (CMD_SEND_REAL_MAIL.equals(actionid)) {
                for (int i = selectedMails.nextSetBit(0); i >= 0; i = selectedMails.nextSetBit(i + 1)) {
                    DBMailLight mail = (DBMailLight) tableCtr.getTableDataModel().getObject(i);
                    MailerResult result = forwardToMyRealMail(mail);
                    if (result.getReturnCode() != MailerResult.OK) {
                        MailHelper.printErrorsAndWarnings(result, getWindowControl(), ureq.getUserSession().getRoles().isOLATAdmin(), getLocale());
                    } else {
                        showInfo("mail.action.send.real.success", mail.getSubject());
                    }
                }
                reloadModel();
            } else if (CMD_MARK_MARKED.equals(actionid) || CMD_MARK_UNMARKED.equals(actionid)) {
                for (int i = selectedMails.nextSetBit(0); i >= 0; i = selectedMails.nextSetBit(i + 1)) {
                    DBMailLight mail = (DBMailLight) tableCtr.getTableDataModel().getObject(i);
                    mailManager.setMarked(mail, CMD_MARK_MARKED.equals(actionid), getIdentity());
                }
                reloadModel();
            } else if (CMD_MARK_READ.equals(actionid) || CMD_MARK_UNREAD.equals(actionid)) {
                for (int i = selectedMails.nextSetBit(0); i >= 0; i = selectedMails.nextSetBit(i + 1)) {
                    DBMailLight mail = (DBMailLight) tableCtr.getTableDataModel().getObject(i);
                    mailManager.setRead(mail, CMD_MARK_READ.equals(actionid), getIdentity());
                }
                reloadModel();
            }
        } else if (TableController.EVENT_FILTER_SELECTED == event) {
            MailDataModel dataModel = (MailDataModel) tableCtr.getTableDataModel();
            MailContextShortName filter = (MailContextShortName) tableCtr.getActiveFilter();
            dataModel.filter(filter);
            tableCtr.setTableDataModel(dataModel);
        } else if (TableController.EVENT_NOFILTER_SELECTED == event) {
            MailDataModel dataModel = (MailDataModel) tableCtr.getTableDataModel();
            dataModel.filter(null);
            tableCtr.setTableDataModel(dataModel);
        }
    } else if (source == mailCtr) {
        backFromMail();
    } else if (source == metaMailCtr) {
        removeAsListenerAndDispose(metaMailCtr);
        metaMailCtr = null;
        mainVC.put(MAIN_CMP, tableVC);
    } else if (source == deleteConfirmationBox) {
        if (DialogBoxUIFactory.isYesEvent(event)) {
            BitSet deleteMails = (BitSet) deleteConfirmationBox.getUserObject();
            for (int i = deleteMails.nextSetBit(0); i >= 0; i = deleteMails.nextSetBit(i + 1)) {
                DBMailLight mail = (DBMailLight) tableCtr.getTableDataModel().getObject(i);
                // reload the message
                mail = mailManager.getMessageByKey(mail.getKey());
                boolean deleteMetaMail = outbox && !StringHelper.containsNonWhitespace(metaId);
                mailManager.delete(mail, getIdentity(), deleteMetaMail);
            // Do not remove from model to prevent concurrent modification
            // exception, instead just reload model afterwards
            }
            reloadModel();
        }
    } else {
        super.event(ureq, source, event);
    }
}
Also used : TableEvent(org.olat.core.gui.components.table.TableEvent) MailerResult(org.olat.core.util.mail.MailerResult) TableMultiSelectEvent(org.olat.core.gui.components.table.TableMultiSelectEvent) BitSet(java.util.BitSet) DBMailLight(org.olat.core.util.mail.model.DBMailLight) DBMailRecipient(org.olat.core.util.mail.model.DBMailRecipient)

Example 38 with MailerResult

use of org.olat.core.util.mail.MailerResult in project OpenOLAT by OpenOLAT.

the class MailManagerImpl method decorateMail.

protected MailContent decorateMail(MailBundle bundle) {
    MailContent content = bundle.getContent();
    String template = getMailTemplate();
    boolean htmlTemplate = StringHelper.isHtml(template);
    String body = content.getBody();
    boolean htmlContent = StringHelper.isHtml(body);
    if (htmlTemplate && !htmlContent) {
        body = body.replace("&", "&amp;");
        body = body.replace("<", "&lt;");
        body = body.replace("\n", "<br />");
    }
    VelocityContext context = new VelocityContext();
    context.put("content", body);
    context.put("footer", MailHelper.getMailFooter(bundle));
    context.put("server", Settings.getServerContextPathURI());
    StringWriter writer = new StringWriter(2000);
    MailerResult result = new MailerResult();
    evaluate(context, template, writer, result);
    String decoratedBody;
    if (result.isSuccessful()) {
        decoratedBody = writer.toString();
    } else {
        decoratedBody = content.getBody();
    }
    return new SimpleMailContent(content.getSubject(), decoratedBody, content.getAttachments());
}
Also used : StringWriter(java.io.StringWriter) MailerResult(org.olat.core.util.mail.MailerResult) VelocityContext(org.apache.velocity.VelocityContext) SimpleMailContent(org.olat.core.util.mail.model.SimpleMailContent) SimpleMailContent(org.olat.core.util.mail.model.SimpleMailContent) MailContent(org.olat.core.util.mail.MailContent)

Example 39 with MailerResult

use of org.olat.core.util.mail.MailerResult in project OpenOLAT by OpenOLAT.

the class CertificatesManagerImpl method doCertificate.

private void doCertificate(JmsCertificateWork workUnit) {
    CertificateImpl certificate = getCertificateById(workUnit.getCertificateKey());
    CertificateTemplate template = null;
    if (workUnit.getTemplateKey() != null) {
        template = getTemplateById(workUnit.getTemplateKey());
    }
    OLATResource resource = certificate.getOlatResource();
    Identity identity = certificate.getIdentity();
    RepositoryEntry entry = repositoryService.loadByResourceKey(resource.getKey());
    String dir = usersStorage.generateDir();
    File dirFile = new File(getCertificateRoot(), dir);
    dirFile.mkdirs();
    Float score = workUnit.getScore();
    String lang = identity.getUser().getPreferences().getLanguage();
    Locale locale = i18nManager.getLocaleOrDefault(lang);
    Boolean passed = workUnit.getPassed();
    Date dateCertification = certificate.getCreationDate();
    Date dateFirstCertification = getDateFirstCertification(identity, resource.getKey());
    Date dateNextRecertification = certificate.getNextRecertificationDate();
    File certificateFile;
    // File name with user name
    StringBuilder sb = new StringBuilder();
    sb.append(identity.getUser().getProperty(UserConstants.LASTNAME, locale)).append("_").append(identity.getUser().getProperty(UserConstants.FIRSTNAME, locale)).append("_").append(entry.getDisplayname()).append("_").append(Formatter.formatShortDateFilesystem(dateCertification));
    String filename = FileUtils.normalizeFilename(sb.toString()) + ".pdf";
    // External URL to certificate as short as possible for QR-Code
    sb = new StringBuilder();
    sb.append(Settings.getServerContextPathURI()).append("/certificate/").append(certificate.getUuid()).append("/certificate.pdf");
    String certUrl = sb.toString();
    if (template == null || template.getPath().toLowerCase().endsWith("pdf")) {
        CertificatePDFFormWorker worker = new CertificatePDFFormWorker(identity, entry, score, passed, dateCertification, dateFirstCertification, dateNextRecertification, certUrl, locale, userManager, this);
        certificateFile = worker.fill(template, dirFile, filename);
        if (certificateFile == null) {
            certificate.setStatus(CertificateStatus.error);
        } else {
            certificate.setStatus(CertificateStatus.ok);
        }
    } else {
        CertificatePhantomWorker worker = new CertificatePhantomWorker(identity, entry, score, passed, dateCertification, dateFirstCertification, dateNextRecertification, certUrl, locale, userManager, this);
        certificateFile = worker.fill(template, dirFile, filename);
        if (certificateFile == null) {
            certificate.setStatus(CertificateStatus.error);
        } else {
            certificate.setStatus(CertificateStatus.ok);
        }
    }
    certificate.setPath(dir + certificateFile.getName());
    if (dateFirstCertification != null) {
        // not the first certification, reset the last of the others certificates
        removeLastFlag(identity, resource.getKey());
    }
    MailerResult result = sendCertificate(identity, entry, certificateFile);
    if (result.isSuccessful()) {
        certificate.setEmailStatus(EmailStatus.ok);
    } else {
        certificate.setEmailStatus(EmailStatus.error);
    }
    dbInstance.getCurrentEntityManager().merge(certificate);
    dbInstance.commit();
    CertificateEvent event = new CertificateEvent(identity.getKey(), certificate.getKey(), resource.getKey());
    coordinatorManager.getCoordinator().getEventBus().fireEventToListenersOf(event, ORES_CERTIFICATE_EVENT);
}
Also used : Locale(java.util.Locale) CertificateTemplate(org.olat.course.certificate.CertificateTemplate) MailerResult(org.olat.core.util.mail.MailerResult) OLATResource(org.olat.resource.OLATResource) CertificateImpl(org.olat.course.certificate.model.CertificateImpl) RepositoryEntry(org.olat.repository.RepositoryEntry) Date(java.util.Date) CertificateEvent(org.olat.course.certificate.CertificateEvent) Identity(org.olat.core.id.Identity) TransientIdentity(org.olat.admin.user.imp.TransientIdentity) File(java.io.File)

Example 40 with MailerResult

use of org.olat.core.util.mail.MailerResult in project OpenOLAT by OpenOLAT.

the class GroupController method doRemoveIdentitiesFromGroup.

private void doRemoveIdentitiesFromGroup(UserRequest ureq, List<Identity> toBeRemoved, MailTemplate mailTemplate) {
    fireEvent(ureq, new IdentitiesRemoveEvent(toBeRemoved));
    identitiesTableModel.remove(toBeRemoved);
    if (tableCtr != null) {
        // can be null in the follwoing case.
        // the user which does the removal is also in the list of toBeRemoved
        // hence the fireEvent does trigger a disposal of a GroupController, which
        // in turn nullifies the tableCtr... see also OLAT-3331
        tableCtr.modelChanged();
    }
    // send the notification mail
    if (mailTemplate != null) {
        // means no sender in footer
        Identity sender = null;
        if (showSenderInRemovMailFooter) {
            sender = ureq.getIdentity();
        }
        String metaId = UUID.randomUUID().toString();
        MailContext context = new MailContextImpl(getWindowControl().getBusinessControl().getAsString());
        MailerResult result = new MailerResult();
        MailBundle[] bundles = mailManager.makeMailBundles(context, toBeRemoved, mailTemplate, sender, metaId, result);
        result.append(mailManager.sendMessage(bundles));
        if (mailTemplate.getCpfrom()) {
            MailBundle ccBundle = mailManager.makeMailBundle(context, ureq.getIdentity(), mailTemplate, sender, metaId, result);
            result.append(mailManager.sendMessage(ccBundle));
        }
        MailHelper.printErrorsAndWarnings(result, getWindowControl(), ureq.getUserSession().getRoles().isOLATAdmin(), ureq.getLocale());
    }
}
Also used : MailContextImpl(org.olat.core.util.mail.MailContextImpl) MailContext(org.olat.core.util.mail.MailContext) MailerResult(org.olat.core.util.mail.MailerResult) Identity(org.olat.core.id.Identity) MailBundle(org.olat.core.util.mail.MailBundle)

Aggregations

MailerResult (org.olat.core.util.mail.MailerResult)140 MailBundle (org.olat.core.util.mail.MailBundle)100 Identity (org.olat.core.id.Identity)82 MailContext (org.olat.core.util.mail.MailContext)66 MailContextImpl (org.olat.core.util.mail.MailContextImpl)66 MailTemplate (org.olat.core.util.mail.MailTemplate)46 Test (org.junit.Test)26 File (java.io.File)24 ArrayList (java.util.ArrayList)20 ContactList (org.olat.core.util.mail.ContactList)20 Locale (java.util.Locale)16 Translator (org.olat.core.gui.translator.Translator)16 VelocityContext (org.apache.velocity.VelocityContext)14 DBMailLight (org.olat.core.util.mail.model.DBMailLight)14 Date (java.util.Date)12 MailPackage (org.olat.core.util.mail.MailPackage)12 List (java.util.List)8 User (org.olat.core.id.User)8 RepositoryEntry (org.olat.repository.RepositoryEntry)8 Property (org.olat.properties.Property)7