Search in sources :

Example 76 with MailerResult

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

the class CourseOverviewController method doAddToRepositoryEntry.

private void doAddToRepositoryEntry(UserRequest ureq, Collection<RepositoryEntry> res, SearchType type, boolean sendEmail) {
    // commit changes to the repository entry
    MailerResult result = new MailerResult();
    MailPackage reMailing = new MailPackage(result, getWindowControl().getBusinessControl().getAsString(), sendEmail);
    RepositoryEntryPermissionChangeEvent changeEvent = new RepositoryEntryPermissionChangeEvent(editedIdentity);
    switch(type) {
        case owner:
            changeEvent.setRepoOwner(Boolean.TRUE);
            break;
        case tutor:
            changeEvent.setRepoTutor(Boolean.TRUE);
            break;
        case participant:
            changeEvent.setRepoParticipant(Boolean.TRUE);
            break;
    }
    List<RepositoryEntryPermissionChangeEvent> repoChanges = Collections.singletonList(changeEvent);
    for (RepositoryEntry repoEntry : res) {
        repositoryManager.updateRepositoryEntryMemberships(getIdentity(), ureq.getUserSession().getRoles(), repoEntry, repoChanges, reMailing);
    }
    // make sure all is committed before loading the model again (I see issues without)
    DBFactory.getInstance().commitAndCloseSession();
    MailHelper.printErrorsAndWarnings(result, getWindowControl(), ureq.getUserSession().getRoles().isOLATAdmin(), getLocale());
}
Also used : MailPackage(org.olat.core.util.mail.MailPackage) MailerResult(org.olat.core.util.mail.MailerResult) RepositoryEntryPermissionChangeEvent(org.olat.repository.model.RepositoryEntryPermissionChangeEvent) RepositoryEntry(org.olat.repository.RepositoryEntry)

Example 77 with MailerResult

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

the class UserDeletionManager method sendUserDeleteEmailTo.

/**
 * Send 'delete'- emails to a list of identities. The delete email is an announcement for the user-deletion.
 *
 * @param selectedIdentities
 * @return String with warning message (e.g. email-address not valid, could not send email).
 *         If there is no warning, the return String is empty ("").
 */
public String sendUserDeleteEmailTo(List<Identity> selectedIdentities, MailTemplate template, boolean isTemplateChanged, String keyEmailSubject, String keyEmailBody, Identity sender, Translator pT) {
    StringBuilder buf = new StringBuilder();
    if (template != null) {
        template.addToContext("responseTo", deletionModule.getEmailResponseTo());
        for (Iterator<Identity> iter = selectedIdentities.iterator(); iter.hasNext(); ) {
            Identity identity = iter.next();
            if (!isTemplateChanged) {
                // Email template has NOT changed => take translated version of subject and body text
                Translator identityTranslator = Util.createPackageTranslator(SelectionController.class, I18nManager.getInstance().getLocaleOrDefault(identity.getUser().getPreferences().getLanguage()));
                template.setSubjectTemplate(identityTranslator.translate(keyEmailSubject));
                template.setBodyTemplate(identityTranslator.translate(keyEmailBody));
            }
            template.putVariablesInMailContext(template.getContext(), identity);
            logDebug(" Try to send Delete-email to identity=" + identity.getName() + " with email=" + identity.getUser().getProperty(UserConstants.EMAIL, null));
            MailerResult result = new MailerResult();
            MailBundle bundle = mailManager.makeMailBundle(null, identity, template, null, null, result);
            if (bundle != null) {
                mailManager.sendMessage(bundle);
            }
            if (template.getCpfrom()) {
                MailBundle ccBundle = mailManager.makeMailBundle(null, sender, template, sender, null, result);
                if (ccBundle != null) {
                    mailManager.sendMessage(ccBundle);
                }
            }
            if (result.getReturnCode() != MailerResult.OK) {
                buf.append(pT.translate("email.error.send.failed", new String[] { identity.getUser().getProperty(UserConstants.EMAIL, null), identity.getName() })).append("\n");
            }
            logAudit("User-Deletion: Delete-email send to identity=" + identity.getName() + " with email=" + identity.getUser().getProperty(UserConstants.EMAIL, null));
            markSendEmailEvent(identity);
        }
    } else {
        // no template => User decides to sending no delete-email, mark only in lifecycle table 'sendEmail'
        for (Iterator<Identity> iter = selectedIdentities.iterator(); iter.hasNext(); ) {
            Identity identity = iter.next();
            logAudit("User-Deletion: Move in 'Email sent' section without sending email, identity=" + identity.getName());
            markSendEmailEvent(identity);
        }
    }
    return buf.toString();
}
Also used : Translator(org.olat.core.gui.translator.Translator) MailerResult(org.olat.core.util.mail.MailerResult) Identity(org.olat.core.id.Identity) MailBundle(org.olat.core.util.mail.MailBundle)

Example 78 with MailerResult

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

the class DENManageParticipantsController method event.

@Override
public void event(UserRequest ureq, Controller source, Event event) {
    if (source == tableListParticipants) {
        if (event.getCommand().equals(Table.COMMANDLINK_ROWACTION_CLICKED)) {
            TableEvent tableEvent = (TableEvent) event;
            // open window for choosen date to manage the enrolled users or manually add
            if (tableEvent.getActionId().equals(DENListTableDataModel.CHANGE_ACTION)) {
                selectedEvent = listTableData.getObject(tableEvent.getRowId());
                List<Identity> participants = denManager.getEventParticipants(selectedEvent);
                participantsTableData = new DENParticipantsTableDataModel(participants);
                removeAsListenerAndDispose(tableManageParticipants);
                tableManageParticipants = denManager.createParticipantsTable(ureq, getWindowControl(), getTranslator(), participantsTableData);
                listenTo(tableManageParticipants);
                participantsVC = createVelocityContainer("participants");
                DateFormat df = new SimpleDateFormat();
                participantsVC.contextPut("dateTitle", selectedEvent.getSubject());
                participantsVC.contextPut("dateTimeframe", df.format(selectedEvent.getBegin()) + " - " + df.format(selectedEvent.getEnd()));
                participantsVC.put("participantsTable", tableManageParticipants.getInitialComponent());
                addParticipantButton = LinkFactory.createButton("participants.add", participantsVC, this);
                removeAsListenerAndDispose(manageParticipantsModalCntrl);
                manageParticipantsModalCntrl = new CloseableModalController(getWindowControl(), "close", participantsVC, true, translate("dates.table.participant.manage"));
                listenTo(manageParticipantsModalCntrl);
                manageParticipantsModalCntrl.activate();
            }
        } else {
            TableMultiSelectEvent tmse = (TableMultiSelectEvent) event;
            BitSet selection = tmse.getSelection();
            // delete all users from the selected dates
            if (tmse.getAction().equals(DENListTableDataModel.DELETE_ACTION) && selection.cardinality() > 0) {
                selectedIds = denManager.getSelectedEventParticipants(dateList, selection);
                dateList = denManager.deleteParticipants(ores, courseNode, denManager.getSelectedEventIDs(dateList, selection));
                listTableData.setObjects(dateList);
                // send notification mail
                createNotificationMail(ureq, courseNode.getShortTitle(), REMOVE_ACTION);
            } else if (tmse.getAction().equals(DENListTableDataModel.MAIL_ACTION) && selection.cardinality() > 0) {
                // send email to all users from the selected dates
                List<Identity> participants = denManager.getSelectedEventParticipants(dateList, selection);
                createParticipantsMail(ureq, participants);
            } else if (selection.cardinality() == 0) {
                showWarning("participants.message.empty");
            }
        }
    } else if (source == userSearchCntrl) {
        if (event == Event.CANCELLED_EVENT) {
            userSearchCMC.deactivate();
        } else {
            List<Identity> toAdd = null;
            selectedIds = new ArrayList<Identity>();
            if (event instanceof SingleIdentityChosenEvent) {
                SingleIdentityChosenEvent singleEvent = (SingleIdentityChosenEvent) event;
                Identity choosenIdentity = singleEvent.getChosenIdentity();
                toAdd = new ArrayList<Identity>();
                toAdd.add(choosenIdentity);
            } else if (event instanceof MultiIdentityChosenEvent) {
                MultiIdentityChosenEvent multiEvent = (MultiIdentityChosenEvent) event;
                toAdd = multiEvent.getChosenIdentities();
            }
            boolean showMessage = false;
            if (toAdd != null && toAdd.size() > 0) {
                for (Identity identity : toAdd) {
                    status = denManager.doEnroll(identity, selectedEvent, ores, courseNode, true);
                    if (!status.isEnrolled() && status.getErrorMessage().equals(DENStatus.ERROR_ALREADY_ENROLLED))
                        showMessage = true;
                    else
                        selectedIds.add(identity);
                }
                if (showMessage)
                    showWarning("enrollment.warning.manual");
                refreshTables();
            }
            userSearchCMC.deactivate();
            if (selectedIds.size() > 0) {
                // write notification mail
                createNotificationMail(ureq, selectedEvent.getSubject(), ADD_ACTION);
            }
        }
    } else if (source == tableManageParticipants) {
        if (event.getCommand().equals(Table.COMMANDLINK_ROWACTION_CLICKED)) {
            TableEvent tableEvent = (TableEvent) event;
            // delete single user from event
            if (tableEvent.getActionId().equals(DENParticipantsTableDataModel.REMOVE_ACTION)) {
                Identity identity = participantsTableData.getEntryAt(tableEvent.getRowId());
                status = denManager.cancelEnroll(identity, selectedEvent, ores);
                if (!status.isCancelled())
                    showError();
                else // send notification mail
                {
                    selectedIds.clear();
                    selectedIds.add(identity);
                    createNotificationMail(ureq, selectedEvent.getSubject(), REMOVE_ACTION);
                }
                refreshTables();
            // write email to single user
            } else if (tableEvent.getActionId().equals(DENParticipantsTableDataModel.MAIL_ACTION)) {
                List<Identity> participants = new ArrayList<Identity>();
                participants.add(participantsTableData.getEntryAt(tableEvent.getRowId()));
                createParticipantsMail(ureq, participants);
            }
        }
    } else if (source == notificationCtr && event == Event.DONE_EVENT) {
        if (notificationCtr.getMailTemplate() != null) {
            Identity sender = ureq.getIdentity();
            MailerResult result = new MailerResult();
            String metaId = UUID.randomUUID().toString().replace("-", "");
            MailContext context = new MailContextImpl(getWindowControl().getBusinessControl().getAsString());
            MailBundle[] bundles = mailManager.makeMailBundles(context, selectedIds, notificationCtr.getMailTemplate(), sender, metaId, result);
            result.append(mailManager.sendMessage(bundles));
            if (notificationCtr.getMailTemplate().getCpfrom()) {
                MailBundle ccBundles = mailManager.makeMailBundle(context, sender, notificationCtr.getMailTemplate(), sender, metaId, result);
                result.append(mailManager.sendMessage(ccBundles));
            }
            MailHelper.printErrorsAndWarnings(result, getWindowControl(), ureq.getUserSession().getRoles().isOLATAdmin(), ureq.getLocale());
        }
        notificationCmc.deactivate();
        selectedIds.clear();
    } else if (source == contactCtr) {
        notificationCmc.deactivate();
    }
}
Also used : MailContextImpl(org.olat.core.util.mail.MailContextImpl) MailerResult(org.olat.core.util.mail.MailerResult) MailContext(org.olat.core.util.mail.MailContext) CloseableModalController(org.olat.core.gui.control.generic.closablewrapper.CloseableModalController) TableMultiSelectEvent(org.olat.core.gui.components.table.TableMultiSelectEvent) BitSet(java.util.BitSet) ArrayList(java.util.ArrayList) TableEvent(org.olat.core.gui.components.table.TableEvent) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) SingleIdentityChosenEvent(org.olat.basesecurity.events.SingleIdentityChosenEvent) ArrayList(java.util.ArrayList) ContactList(org.olat.core.util.mail.ContactList) List(java.util.List) Identity(org.olat.core.id.Identity) MultiIdentityChosenEvent(org.olat.basesecurity.events.MultiIdentityChosenEvent) MailBundle(org.olat.core.util.mail.MailBundle) SimpleDateFormat(java.text.SimpleDateFormat)

Example 79 with MailerResult

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

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)

Example 80 with MailerResult

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

the class ProfileFormController method createChangeEmailWorkflow.

private void createChangeEmailWorkflow(UserRequest ureq) {
    // send email
    changedEmail = changedEmail.trim();
    String body = null;
    String subject = null;
    // get remote address
    String ip = ureq.getHttpReq().getRemoteAddr();
    String today = DateFormat.getDateInstance(DateFormat.LONG, ureq.getLocale()).format(new Date());
    // mailer configuration
    String serverpath = Settings.getServerContextPathURI();
    String servername = ureq.getHttpReq().getServerName();
    logDebug("this servername is " + servername + " and serverpath is " + serverpath, null);
    // load or create temporary key
    Map<String, String> mailMap = new HashMap<>();
    mailMap.put("currentEMail", currentEmail);
    mailMap.put("changedEMail", changedEmail);
    XStream xml = XStreamHelper.createXStreamInstance();
    String serMailMap = xml.toXML(mailMap);
    TemporaryKey tk = rm.createAndDeleteOldTemporaryKey(identityToModify.getKey(), serMailMap, ip, RegistrationManager.EMAIL_CHANGE);
    // create date, time string
    Calendar cal = Calendar.getInstance();
    cal.setTime(tk.getCreationDate());
    cal.add(Calendar.DAY_OF_WEEK, ChangeEMailController.TIME_OUT);
    String time = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, ureq.getLocale()).format(cal.getTime());
    // create body and subject for email
    String link = serverpath + "/dmz/emchange/index.html?key=" + tk.getRegistrationKey() + "&language=" + ureq.getLocale().getLanguage();
    if (Settings.isDebuging()) {
        logInfo(link, null);
    }
    String currentEmailDisplay = userManager.getUserDisplayEmail(currentEmail, getLocale());
    String changedEmaildisplay = userManager.getUserDisplayEmail(changedEmail, getLocale());
    body = translate("email.change.body", new String[] { link, time, currentEmailDisplay, changedEmaildisplay }) + SEPARATOR + translate("email.change.wherefrom", new String[] { serverpath, today, ip });
    subject = translate("email.change.subject");
    // send email
    try {
        MailBundle bundle = new MailBundle();
        bundle.setFrom(WebappHelper.getMailConfig("mailReplyTo"));
        bundle.setTo(changedEmail);
        bundle.setContent(subject, body);
        MailerResult result = mailManager.sendMessage(bundle);
        boolean isMailSent = result.isSuccessful();
        if (isMailSent) {
            tk.setMailSent(true);
            // set key
            User user = this.identityToModify.getUser();
            user.setProperty("emchangeKey", tk.getRegistrationKey());
            UserManager.getInstance().updateUser(user);
            getWindowControl().setInfo(translate("email.sent"));
        } else {
            tk.setMailSent(false);
            rm.deleteTemporaryKeyWithId(tk.getRegistrationKey());
            getWindowControl().setError(translate("email.notsent"));
        }
    } catch (Exception e) {
        rm.deleteTemporaryKeyWithId(tk.getRegistrationKey());
        getWindowControl().setError(translate("email.notsent"));
    }
}
Also used : User(org.olat.core.id.User) HashMap(java.util.HashMap) MailerResult(org.olat.core.util.mail.MailerResult) XStream(com.thoughtworks.xstream.XStream) TemporaryKey(org.olat.registration.TemporaryKey) Calendar(java.util.Calendar) MailBundle(org.olat.core.util.mail.MailBundle) Date(java.util.Date)

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