Search in sources :

Example 41 with MailBundle

use of org.olat.core.util.mail.MailBundle in project openolat by klemens.

the class InvitationEditRightsController method sendInvitation.

private void sendInvitation() {
    String inviteeEmail = invitee.getUser().getProperty(UserConstants.EMAIL, getLocale());
    ContactList contactList = new ContactList(inviteeEmail);
    contactList.add(inviteeEmail);
    boolean success = false;
    try {
        mailTemplate.setSubjectTemplate(subjectEl.getValue());
        mailTemplate.setBodyTemplate(bodyEl.getValue());
        MailContext context = new MailContextImpl(binder, null, getWindowControl().getBusinessControl().getAsString());
        MailBundle bundle = new MailBundle();
        bundle.setContext(context);
        bundle.setFromId(getIdentity());
        bundle.setContactList(contactList);
        bundle.setContent(subjectEl.getValue(), bodyEl.getValue());
        MailerResult result = mailManager.sendExternMessage(bundle, null, true);
        success = result.isSuccessful();
    } catch (Exception e) {
        logError("Error on sending invitation mail to contactlist, invalid address.", e);
    }
    if (success) {
        showInfo("invitation.mail.success");
    } else {
        showError("invitation.mail.failure");
    }
}
Also used : MailContextImpl(org.olat.core.util.mail.MailContextImpl) MailContext(org.olat.core.util.mail.MailContext) MailerResult(org.olat.core.util.mail.MailerResult) ContactList(org.olat.core.util.mail.ContactList) MailBundle(org.olat.core.util.mail.MailBundle)

Example 42 with MailBundle

use of org.olat.core.util.mail.MailBundle in project openolat by klemens.

the class RegistrationController method event.

/**
 * @see org.olat.core.gui.control.DefaultController#event(org.olat.core.gui.UserRequest, org.olat.core.gui.control.Controller, org.olat.core.gui.control.Event)
 */
@Override
public void event(UserRequest ureq, Controller source, Event event) {
    if (source == emailSendForm) {
        if (event == Event.DONE_EVENT) {
            // form
            // validation
            // was ok
            wizInfoController.setCurStep(2);
            // Email requested for tempkey
            // save the fields somewhere
            String email = emailSendForm.getEmailAddress();
            myContent.contextPut("email", email);
            myContent.contextPut("text", translate("step2.reg.text", email));
            // ef.setVisible(false);
            regarea.setVisible(false);
            // get remote address
            String ip = ureq.getHttpReq().getRemoteAddr();
            String serverpath = Settings.getServerContextPathURI();
            String today = DateFormat.getDateInstance(DateFormat.LONG, ureq.getLocale()).format(new Date());
            String[] whereFromAttrs = new String[] { serverpath, today, ip };
            boolean isMailSent = false;
            if (registrationManager.isRegistrationPending(email) || UserManager.getInstance().isEmailAllowed(email)) {
                TemporaryKey tk = null;
                if (userModule.isEmailUnique()) {
                    tk = registrationManager.loadTemporaryKeyByEmail(email);
                }
                if (tk == null)
                    tk = registrationManager.loadOrCreateTemporaryKeyByEmail(email, ip, RegistrationManager.REGISTRATION);
                myContent.contextPut("regKey", tk.getRegistrationKey());
                String link = serverpath + "/dmz/registration/index.html?key=" + tk.getRegistrationKey() + "&language=" + i18nModule.getLocaleKey(ureq.getLocale());
                String[] bodyAttrs = new String[] { // 0
                serverpath, // 1
                tk.getRegistrationKey(), // 2
                i18nModule.getLocaleKey(ureq.getLocale()), // 3
                "<a href=\"" + link + "\">" + link + "</a>" };
                String body = translate("reg.body", bodyAttrs);
                boolean htmlBody = StringHelper.isHtml(body);
                if (!htmlBody) {
                    body += SEPARATOR + translate("reg.wherefrom", whereFromAttrs);
                }
                try {
                    MailBundle bundle = new MailBundle();
                    bundle.setTo(email);
                    bundle.setContent(translate("reg.subject"), body);
                    MailerResult result = mailManager.sendExternMessage(bundle, null, htmlBody);
                    if (result.isSuccessful()) {
                        isMailSent = true;
                    }
                } catch (Exception e) {
                // nothing to do, emailSent flag is false, errors will be reported to user
                }
            } else {
                // if users with this email address exists, they are informed.
                List<Identity> identities = UserManager.getInstance().findIdentitiesByEmail(Collections.singletonList(email));
                for (Identity identity : identities) {
                    String body = translate("login.body", identity.getName()) + SEPARATOR + translate("reg.wherefrom", whereFromAttrs);
                    try {
                        MailBundle bundle = new MailBundle();
                        bundle.setTo(email);
                        bundle.setContent(translate("login.subject"), body);
                        MailerResult result = mailManager.sendExternMessage(bundle, null, true);
                        if (result.isSuccessful()) {
                            isMailSent = true;
                        }
                    } catch (Exception e) {
                    // nothing to do, emailSent flag is false, errors will be reported to user
                    }
                }
            }
            if (isMailSent) {
                showInfo("email.sent");
            } else {
                showError("email.notsent");
            }
        } else if (event == Event.CANCELLED_EVENT) {
            fireEvent(ureq, Event.CANCELLED_EVENT);
        }
    } else if (source == langChooserController) {
        if (event == Event.DONE_EVENT) {
            wizInfoController.setCurStep(2);
            createEmailForm(ureq);
            ureq.getUserSession().removeEntry(LocaleNegotiator.NEGOTIATED_LOCALE);
        } else if (event == Event.CANCELLED_EVENT) {
            ureq.getDispatchResult().setResultingMediaResource(new RedirectMediaResource(Settings.getServerContextPathURI()));
        } else if (event instanceof LanguageChangedEvent) {
            LanguageChangedEvent lcev = (LanguageChangedEvent) event;
            setLocale(lcev.getNewLocale(), true);
            myContent.contextPut("text", translate("select.language.description"));
        }
    } else if (source == registrationForm) {
        // Userdata entered
        if (event == Event.DONE_EVENT) {
            String lang = registrationForm.getLangKey();
            // change language if different then current language
            if (!lang.equals(i18nModule.getLocaleKey(ureq.getLocale()))) {
                Locale loc = i18nManager.getLocaleOrDefault(lang);
                ureq.getUserSession().setLocale(loc);
                getTranslator().setLocale(loc);
            }
            wizInfoController.setCurStep(4);
            myContent.contextPut("pwdhelp", "");
            myContent.contextPut("loginhelp", "");
            myContent.contextPut("text", translate("step4.reg.text"));
            removeAsListenerAndDispose(disclaimerController);
            disclaimerController = new DisclaimerController(ureq, getWindowControl());
            listenTo(disclaimerController);
            regarea.setContent(disclaimerController.getInitialComponent());
        } else if (event == Event.CANCELLED_EVENT) {
            ureq.getDispatchResult().setResultingMediaResource(new RedirectMediaResource(Settings.getServerContextPathURI()));
        }
    } else if (source == disclaimerController) {
        if (event == Event.DONE_EVENT) {
            // finalize the registration by creating the user
            Identity persitedIdentity = createNewUserAfterRegistration();
            // display step5
            displayFinalStep(persitedIdentity);
        } else if (event == Event.CANCELLED_EVENT) {
            ureq.getDispatchResult().setResultingMediaResource(new RedirectMediaResource(Settings.getServerContextPathURI()));
        }
    }
}
Also used : Locale(java.util.Locale) MailerResult(org.olat.core.util.mail.MailerResult) LanguageChangedEvent(org.olat.core.commons.chiefcontrollers.LanguageChangedEvent) Date(java.util.Date) RedirectMediaResource(org.olat.core.gui.media.RedirectMediaResource) MailBundle(org.olat.core.util.mail.MailBundle) Identity(org.olat.core.id.Identity)

Example 43 with MailBundle

use of org.olat.core.util.mail.MailBundle in project openolat by klemens.

the class RegistrationWebService method register.

/**
 * Register with the specified email
 * @response.representation.200.doc Registration successful
 * @response.representation.304.doc Already registered, HTTP-Header location set to redirect
 * @response.representation.400.doc Email address not allowed
 * @param email The email address
 * @param request The HTTP Request
 * @return
 */
@PUT
public Response register(@QueryParam("email") String email, @Context HttpServletRequest request) {
    if (!CoreSpringFactory.getImpl(RegistrationModule.class).isSelfRegistrationEnabled()) {
        return Response.serverError().status(Status.NOT_FOUND).build();
    }
    ResponseBuilder response;
    Locale locale = getLocale(request);
    Translator translator = getTranslator(locale);
    MailManager mailM = CoreSpringFactory.getImpl(MailManager.class);
    UserManager userManager = UserManager.getInstance();
    RegistrationManager rm = CoreSpringFactory.getImpl(RegistrationManager.class);
    boolean foundUser = userManager.findUniqueIdentityByEmail(email) != null;
    boolean noNewUserWithEmail = !userManager.isEmailAllowed(email);
    String serverpath = Settings.getServerContextPathURI();
    if (foundUser && noNewUserWithEmail) {
        // redirect
        URI redirectUri = UriBuilder.fromUri(Settings.getServerContextPathURI()).build();
        response = Response.ok().status(Status.NOT_MODIFIED).location(redirectUri);
    } else if (userManager.isEmailAllowed(email)) {
        String ip = request.getRemoteAddr();
        TemporaryKey tk = null;
        UserModule userModule = CoreSpringFactory.getImpl(UserModule.class);
        if (userModule.isEmailUnique()) {
            tk = rm.loadTemporaryKeyByEmail(email);
        }
        if (tk == null) {
            tk = rm.loadOrCreateTemporaryKeyByEmail(email, ip, RegistrationManager.REGISTRATION);
        }
        String today = DateFormat.getDateInstance(DateFormat.LONG, locale).format(new Date());
        String[] bodyAttrs = new String[] { serverpath, tk.getRegistrationKey(), CoreSpringFactory.getImpl(I18nModule.class).getLocaleKey(locale) };
        String[] whereFromAttrs = new String[] { serverpath, today, ip };
        String body = translator.translate("reg.body", bodyAttrs) + SEPARATOR + translator.translate("reg.wherefrom", whereFromAttrs);
        try {
            MailBundle bundle = new MailBundle();
            bundle.setTo(email);
            bundle.setContent(translator.translate("reg.subject"), body);
            MailerResult result = mailM.sendExternMessage(bundle, null, true);
            if (result.isSuccessful()) {
                response = Response.ok();
            } else {
                response = Response.serverError().status(Status.INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            response = Response.serverError().status(Status.INTERNAL_SERVER_ERROR);
            log.error("", e);
        }
    } else {
        response = Response.serverError().status(Status.BAD_REQUEST);
    }
    return response.build();
}
Also used : Locale(java.util.Locale) RestSecurityHelper.getLocale(org.olat.restapi.security.RestSecurityHelper.getLocale) RegistrationManager(org.olat.registration.RegistrationManager) MailerResult(org.olat.core.util.mail.MailerResult) TemporaryKey(org.olat.registration.TemporaryKey) URI(java.net.URI) Date(java.util.Date) Translator(org.olat.core.gui.translator.Translator) UserManager(org.olat.user.UserManager) MailManager(org.olat.core.util.mail.MailManager) UserModule(org.olat.user.UserModule) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) MailBundle(org.olat.core.util.mail.MailBundle) PUT(javax.ws.rs.PUT)

Example 44 with MailBundle

use of org.olat.core.util.mail.MailBundle in project openolat by klemens.

the class UnpublishResourceCallback method execute.

@Override
public Step execute(UserRequest ureq, WindowControl wControl, StepsRunContext runContext) {
    MailTemplate mailTemplate = (MailTemplate) runContext.get("mailTemplate");
    if (mailTemplate != null) {
        List<Identity> ownerList = new ArrayList<Identity>();
        // owners
        if (repositoryService.hasRole(ureq.getIdentity(), repositoryEntry, GroupRoles.owner.name())) {
            ownerList = repositoryService.getMembers(repositoryEntry, GroupRoles.owner.name());
        }
        String businessPath = wControl.getBusinessControl().getAsString();
        MailContext context = new MailContextImpl(businessPath);
        String metaId = UUID.randomUUID().toString().replace("-", "");
        MailerResult result = new MailerResult();
        MailBundle[] bundles = mailManager.makeMailBundles(context, ownerList, mailTemplate, ureq.getIdentity(), metaId, result);
        result.append(mailManager.sendMessage(bundles));
        if (mailTemplate.getCpfrom()) {
            MailBundle ccBundle = mailManager.makeMailBundle(context, ureq.getIdentity(), mailTemplate, ureq.getIdentity(), metaId, result);
            result.append(mailManager.sendMessage(ccBundle));
        }
        StringBuilder errorMessage = new StringBuilder();
        StringBuilder warningMessage = new StringBuilder();
        MailHelper.appendErrorsAndWarnings(result, errorMessage, warningMessage, ureq.getUserSession().getRoles().isOLATAdmin(), ureq.getLocale());
        if (warningMessage.length() > 0) {
            wControl.setWarning(warningMessage.toString());
        }
        if (errorMessage.length() > 0) {
            wControl.setError(errorMessage.toString());
        }
        ownerList.clear();
    }
    // update status
    repositoryEntry = repositoryService.loadByKey(repositoryEntry.getKey());
    repositoryEntry.setStatusCode(RepositoryEntryStatus.REPOSITORY_STATUS_CLOSED);
    repositoryEntry = DBFactory.getInstance().getCurrentEntityManager().merge(repositoryEntry);
    // clean catalog
    Object cleanCatalog = runContext.get("cleanCatalog");
    if (cleanCatalog != null && Boolean.TRUE.equals(cleanCatalog)) {
        CoreSpringFactory.getImpl(CatalogManager.class).resourceableDeleted(repositoryEntry);
    }
    // clean groups
    Object cleanGroups = runContext.get("cleanGroups");
    if (cleanGroups != null && Boolean.TRUE.equals(cleanGroups)) {
        doCleanGroups(ureq.getIdentity());
    }
    ThreadLocalUserActivityLogger.log(CourseLoggingAction.COURSE_EDITOR_CLOSE, getClass());
    log.audit("Repository entry " + repositoryEntry.getDisplayname() + " ( " + repositoryEntry.getOlatResource() + " ) closed");
    return StepsMainRunController.DONE_MODIFIED;
}
Also used : MailContextImpl(org.olat.core.util.mail.MailContextImpl) MailContext(org.olat.core.util.mail.MailContext) MailerResult(org.olat.core.util.mail.MailerResult) ArrayList(java.util.ArrayList) CatalogManager(org.olat.repository.manager.CatalogManager) MailTemplate(org.olat.core.util.mail.MailTemplate) Identity(org.olat.core.id.Identity) MailBundle(org.olat.core.util.mail.MailBundle)

Example 45 with MailBundle

use of org.olat.core.util.mail.MailBundle in project openolat by klemens.

the class ReminderServiceImpl method sendReminder.

@Override
public MailerResult sendReminder(Reminder reminder, List<Identity> identitiesToRemind) {
    RepositoryEntry entry = reminder.getEntry();
    ContactList contactList = new ContactList("Infos");
    contactList.addAllIdentites(identitiesToRemind);
    MailContext context = new MailContextImpl("[RepositoryEntry:" + entry.getKey() + "]");
    Locale locale = I18nModule.getDefaultLocale();
    Translator trans = Util.createPackageTranslator(ReminderAdminController.class, locale);
    String subject = reminder.getEmailSubject();
    String body = reminder.getEmailBody();
    if (body.contains("$courseurl")) {
        body = body.replace("$courseurl", "<a href=\"$courseurl\">$courseurl</a>");
    } else {
        body = body + "<p>---<br />" + trans.translate("reminder.from.course", new String[] { "<a href=\"$courseurl\">$coursename</a>" }) + "</p>";
    }
    String metaId = UUID.randomUUID().toString();
    String url = Settings.getServerContextPathURI() + "/url/RepositoryEntry/" + entry.getKey();
    MailerResult overviewResult = new MailerResult();
    ReminderTemplate template = new ReminderTemplate(subject, body, url, entry, locale);
    for (Identity identityToRemind : identitiesToRemind) {
        String status;
        MailBundle bundle = mailManager.makeMailBundle(context, identityToRemind, template, null, metaId, overviewResult);
        MailerResult result = mailManager.sendMessage(bundle);
        overviewResult.append(result);
        List<Identity> failedIdentities = result.getFailedIdentites();
        if (failedIdentities != null && failedIdentities.contains(identityToRemind)) {
            status = "error";
        } else {
            status = "ok";
        }
        reminderDao.markAsSend(reminder, identityToRemind, status);
    }
    return overviewResult;
}
Also used : Locale(java.util.Locale) MailContextImpl(org.olat.core.util.mail.MailContextImpl) MailContext(org.olat.core.util.mail.MailContext) Translator(org.olat.core.gui.translator.Translator) MailerResult(org.olat.core.util.mail.MailerResult) RepositoryEntry(org.olat.repository.RepositoryEntry) ContactList(org.olat.core.util.mail.ContactList) Identity(org.olat.core.id.Identity) MailBundle(org.olat.core.util.mail.MailBundle)

Aggregations

MailBundle (org.olat.core.util.mail.MailBundle)126 MailerResult (org.olat.core.util.mail.MailerResult)100 Identity (org.olat.core.id.Identity)72 MailContextImpl (org.olat.core.util.mail.MailContextImpl)72 MailContext (org.olat.core.util.mail.MailContext)70 MailTemplate (org.olat.core.util.mail.MailTemplate)32 Translator (org.olat.core.gui.translator.Translator)28 ContactList (org.olat.core.util.mail.ContactList)28 Locale (java.util.Locale)20 File (java.io.File)18 Date (java.util.Date)16 Test (org.junit.Test)14 MailManager (org.olat.core.util.mail.MailManager)14 DBMailLight (org.olat.core.util.mail.model.DBMailLight)12 ArrayList (java.util.ArrayList)10 Property (org.olat.properties.Property)7 ContextEntry (org.olat.core.id.context.ContextEntry)6 AssertException (org.olat.core.logging.AssertException)6 TemporaryKey (org.olat.registration.TemporaryKey)6 UserManager (org.olat.user.UserManager)6