Search in sources :

Example 6 with MailException

use of org.springframework.mail.MailException in project perun by CESNET.

the class MailManagerImpl method sendMessage.

@Override
public void sendMessage(Application app, MailType mailType, String reason, List<Exception> exceptions) {
    try {
        // get form
        ApplicationForm form;
        if (app.getGroup() != null) {
            form = registrarManager.getFormForGroup(app.getGroup());
        } else {
            form = registrarManager.getFormForVo(app.getVo());
        }
        // get mail definition
        ApplicationMail mail = getMailByParams(form.getId(), app.getType(), mailType);
        if (mail == null) {
            log.error("[MAIL MANAGER] Mail not sent. Definition (or mail text) for: {} do not exists for VO: " + app.getVo() + " and Group: " + app.getGroup(), mailType.toString());
            // mail not found
            return;
        } else if (mail.getSend() == false) {
            log.info("[MAIL MANAGER] Mail not sent. Disabled by VO admin for: " + mail.getMailType() + " / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup());
            // sending this mail is disabled by VO admin
            return;
        }
        // get app data
        List<ApplicationFormItemData> data = registrarManager.getApplicationDataById(registrarSession, app.getId());
        // get language
        Locale lang = new Locale(getLanguageFromAppData(app, data));
        // get localized subject and text
        MailText mt = mail.getMessage(lang);
        String mailText = "";
        String mailSubject = "";
        if (mt.getText() != null && !mt.getText().isEmpty()) {
            mailText = mt.getText();
        }
        if (mt.getSubject() != null && !mt.getSubject().isEmpty()) {
            mailSubject = mt.getSubject();
        }
        // different behavior based on mail type
        MailType type = mail.getMailType();
        if (MailType.APP_CREATED_USER.equals(type)) {
            SimpleMailMessage message = new SimpleMailMessage();
            // set FROM
            setFromMailAddress(message, app);
            // set TO
            setUsersMailAsTo(message, app, data);
            // substitute common strings
            mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
            mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
            // set subject and text
            message.setSubject(mailSubject);
            message.setText(mailText);
            try {
                // send mail
                mailSender.send(message);
                log.info("[MAIL MANAGER] Sending mail: APP_CREATED_USER to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
            } catch (MailException ex) {
                log.error("[MAIL MANAGER] Sending mail: APP_CREATED_USER failed because of exception: {}", ex);
            }
        } else if (MailType.APP_CREATED_VO_ADMIN.equals(type)) {
            SimpleMailMessage message = new SimpleMailMessage();
            // set FROM
            setFromMailAddress(message, app);
            // set language independent on user's preferred language.
            lang = new Locale("en");
            try {
                if (app.getGroup() == null) {
                    // VO
                    Attribute a = attrManager.getAttribute(registrarSession, app.getVo(), URN_VO_LANGUAGE_EMAIL);
                    if (a != null && a.getValue() != null) {
                        lang = new Locale(BeansUtils.attributeValueToString(a));
                    }
                } else {
                    Attribute a = attrManager.getAttribute(registrarSession, app.getGroup(), URN_GROUP_LANGUAGE_EMAIL);
                    if (a != null && a.getValue() != null) {
                        lang = new Locale(BeansUtils.attributeValueToString(a));
                    }
                }
            } catch (Exception ex) {
                log.error("Error when resolving notification default language: {}", ex);
            }
            MailText mt2 = mail.getMessage(lang);
            String mailText2 = "";
            String mailSubject2 = "";
            if (mt2.getText() != null && !mt2.getText().isEmpty()) {
                mailText2 = mt2.getText();
            }
            if (mt2.getSubject() != null && !mt2.getSubject().isEmpty()) {
                mailSubject2 = mt2.getSubject();
            }
            // substitute common strings
            mailText2 = substituteCommonStrings(app, data, mailText2, reason, exceptions);
            mailSubject2 = substituteCommonStrings(app, data, mailSubject2, reason, exceptions);
            // set subject and text
            message.setSubject(mailSubject2);
            message.setText(mailText2);
            // send message to all VO or Group admins
            List<String> toEmail = getToMailAddresses(app);
            for (String email : toEmail) {
                message.setTo(email);
                try {
                    mailSender.send(message);
                    log.info("[MAIL MANAGER] Sending mail: APP_CREATED_VO_ADMIN to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
                } catch (MailException ex) {
                    log.error("[MAIL MANAGER] Sending mail: APP_CREATED_VO_ADMIN failed because of exception: {}", ex);
                }
            }
        } else if (MailType.MAIL_VALIDATION.equals(type)) {
            SimpleMailMessage message = new SimpleMailMessage();
            // set FROM
            setFromMailAddress(message, app);
            // set TO
            // empty = not sent
            message.setTo("");
            // substitute common strings
            mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
            mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
            // set subject and text
            message.setSubject(mailSubject);
            // send to all emails, which needs to be validated
            for (ApplicationFormItemData d : data) {
                ApplicationFormItem item = d.getFormItem();
                String value = d.getValue();
                // if mail field and not validated
                if (ApplicationFormItem.Type.VALIDATED_EMAIL.equals(item.getType()) && !"1".equals(d.getAssuranceLevel())) {
                    if (value != null && !value.isEmpty()) {
                        // set TO
                        message.setTo(value);
                        // get validation link params
                        String i = Integer.toString(d.getId(), Character.MAX_RADIX);
                        String m = getMessageAuthenticationCode(i);
                        // replace new validation link
                        if (mailText.contains("{validationLink-")) {
                            Pattern pattern = Pattern.compile("\\{validationLink-[^\\}]+\\}");
                            Matcher matcher = pattern.matcher(mailText);
                            while (matcher.find()) {
                                // whole "{validationLink-something}"
                                String toSubstitute = matcher.group(0);
                                // new login value to replace in text
                                String newValue = "";
                                Pattern namespacePattern = Pattern.compile("\\-(.*?)\\}");
                                Matcher m2 = namespacePattern.matcher(toSubstitute);
                                while (m2.find()) {
                                    // only namespace "fed", "cert",...
                                    String namespace = m2.group(1);
                                    newValue = getPerunUrl(app.getVo(), app.getGroup());
                                    if (newValue != null && !newValue.isEmpty()) {
                                        if (!newValue.endsWith("/"))
                                            newValue += "/";
                                        newValue += namespace + "/registrar/";
                                        newValue += "?vo=" + getEncodedString(app.getVo().getShortName());
                                        newValue += ((app.getGroup() != null) ? "&group=" + getEncodedString(app.getGroup().getName()) : "");
                                        try {
                                            newValue += "&i=" + URLEncoder.encode(i, "UTF-8") + "&m=" + URLEncoder.encode(m, "UTF-8");
                                        } catch (UnsupportedEncodingException ex) {
                                            newValue += "&i=" + i + "&m=" + m;
                                        }
                                    }
                                }
                                // substitute {validationLink-authz} with actual value or empty string
                                mailText = mailText.replace(toSubstitute, newValue);
                            }
                        }
                        if (mailText.contains("{validationLink}")) {
                            // new backup if validation URL is missing
                            String url = getPerunUrl(app.getVo(), app.getGroup());
                            if (url != null && !url.isEmpty()) {
                                if (!url.endsWith("/"))
                                    url += "/";
                                url += "registrar/";
                            }
                            if (url != null && !url.isEmpty())
                                url = url + "?vo=" + getEncodedString(app.getVo().getShortName());
                            if (app.getGroup() != null) {
                                // append group name for
                                if (url != null && !url.isEmpty())
                                    url += "&group=" + getEncodedString(app.getGroup().getName());
                            }
                            // construct whole url
                            StringBuilder url2 = new StringBuilder(url);
                            if (url.contains("?")) {
                                if (!url.endsWith("?")) {
                                    url2.append("&");
                                }
                            } else {
                                if (!url2.toString().isEmpty())
                                    url2.append("?");
                            }
                            try {
                                if (!url2.toString().isEmpty())
                                    url2.append("i=").append(URLEncoder.encode(i, "UTF-8")).append("&m=").append(URLEncoder.encode(m, "UTF-8"));
                            } catch (UnsupportedEncodingException ex) {
                                if (!url2.toString().isEmpty())
                                    url2.append("i=").append(i).append("&m=").append(m);
                            }
                            // replace validation link
                            mailText = mailText.replace("{validationLink}", url2.toString());
                        }
                        // set replaced text
                        message.setText(mailText);
                        try {
                            mailSender.send(message);
                            log.info("[MAIL MANAGER] Sending mail: MAIL_VALIDATION to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
                        } catch (MailException ex) {
                            log.error("[MAIL MANAGER] Sending mail: MAIL_VALIDATION failed because of exception: {}", ex);
                        }
                    } else {
                        log.error("[MAIL MANAGER] Sending mail: MAIL_VALIDATION failed. Not valid value of VALIDATED_MAIL field: {}", value);
                    }
                }
            }
        } else if (type.equals(MailType.APP_APPROVED_USER)) {
            SimpleMailMessage message = new SimpleMailMessage();
            // set FROM
            setFromMailAddress(message, app);
            // set TO
            setUsersMailAsTo(message, app, data);
            // substitute common strings
            mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
            mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
            // set subject and text
            message.setSubject(mailSubject);
            message.setText(mailText);
            try {
                // send mail
                mailSender.send(message);
                log.info("[MAIL MANAGER] Sending mail: APP_APPROVED_USER to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
            } catch (MailException ex) {
                log.error("[MAIL MANAGER] Sending mail: APP_APPROVED_USER failed because of exception: {}", ex);
            }
        } else if (type.equals(MailType.APP_REJECTED_USER)) {
            SimpleMailMessage message = new SimpleMailMessage();
            // set FROM
            setFromMailAddress(message, app);
            // set TO
            setUsersMailAsTo(message, app, data);
            // substitute common strings
            mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
            mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
            // set subject and text
            message.setSubject(mailSubject);
            message.setText(mailText);
            try {
                // send mail
                mailSender.send(message);
                log.info("[MAIL MANAGER] Sending mail: APP_REJECTED_USER to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
            } catch (MailException ex) {
                log.error("[MAIL MANAGER] Sending mail: APP_REJECTED_USER failed because of exception: {}", ex);
            }
        } else if (MailType.APP_ERROR_VO_ADMIN.equals(type)) {
            SimpleMailMessage message = new SimpleMailMessage();
            // set FROM
            setFromMailAddress(message, app);
            // set language independent on user's preferred language.
            lang = new Locale("en");
            try {
                if (app.getGroup() == null) {
                    // VO
                    Attribute a = attrManager.getAttribute(registrarSession, app.getVo(), URN_VO_LANGUAGE_EMAIL);
                    if (a != null && a.getValue() != null) {
                        lang = new Locale(BeansUtils.attributeValueToString(a));
                    }
                } else {
                    Attribute a = attrManager.getAttribute(registrarSession, app.getGroup(), URN_GROUP_LANGUAGE_EMAIL);
                    if (a != null && a.getValue() != null) {
                        lang = new Locale(BeansUtils.attributeValueToString(a));
                    }
                }
            } catch (Exception ex) {
                log.error("Error when resolving notification default language: {}", ex);
            }
            MailText mt2 = mail.getMessage(lang);
            String mailText2 = "";
            String mailSubject2 = "";
            if (mt2.getText() != null && !mt2.getText().isEmpty()) {
                mailText2 = mt2.getText();
            }
            if (mt2.getSubject() != null && !mt2.getSubject().isEmpty()) {
                mailSubject2 = mt2.getSubject();
            }
            // substitute common strings
            mailText2 = substituteCommonStrings(app, data, mailText2, reason, exceptions);
            mailSubject2 = substituteCommonStrings(app, data, mailSubject2, reason, exceptions);
            // set subject and text
            message.setSubject(mailSubject2);
            message.setText(mailText2);
            // send message to all VO or Group admins
            List<String> toEmail = getToMailAddresses(app);
            for (String email : toEmail) {
                message.setTo(email);
                try {
                    mailSender.send(message);
                    log.info("[MAIL MANAGER] Sending mail: APP_ERROR_VO_ADMIN to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
                } catch (MailException ex) {
                    log.error("[MAIL MANAGER] Sending mail: APP_ERROR_VO_ADMIN failed because of exception: {}", ex);
                }
            }
        } else {
            log.error("[MAIL MANAGER] Sending mail type: {} is not supported.", type);
        }
    } catch (Exception ex) {
        // all exceptions are catched and logged to: perun-registrar.log
        log.error("[MAIL MANAGER] Exception thrown when sending email: {}", ex);
    }
}
Also used : ApplicationForm(cz.metacentrum.perun.registrar.model.ApplicationForm) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ApplicationFormItemData(cz.metacentrum.perun.registrar.model.ApplicationFormItemData) MailType(cz.metacentrum.perun.registrar.model.ApplicationMail.MailType) SQLException(java.sql.SQLException) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) RegistrarException(cz.metacentrum.perun.registrar.exceptions.RegistrarException) DuplicateKeyException(org.springframework.dao.DuplicateKeyException) MailException(org.springframework.mail.MailException) ApplicationFormItem(cz.metacentrum.perun.registrar.model.ApplicationFormItem) SimpleMailMessage(org.springframework.mail.SimpleMailMessage) MailText(cz.metacentrum.perun.registrar.model.ApplicationMail.MailText) MailException(org.springframework.mail.MailException) ApplicationMail(cz.metacentrum.perun.registrar.model.ApplicationMail)

Example 7 with MailException

use of org.springframework.mail.MailException in project ocvn by devgateway.

the class SendEmailService method sendEmailResetPassword.

/**
     * Send a reset password email. This is UNSAFE because passwords are sent in clear text.
     * Nevertheless some customers will ask for these emails to be sent, so ...
     * @param person
     * @param newPassword
     */
public void sendEmailResetPassword(final Person person, final String newPassword) {
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setTo(person.getEmail());
    msg.setFrom("support@developmentgateway.org");
    msg.setSubject("Recover your password");
    msg.setText("Dear " + person.getFirstName() + " " + person.getLastName() + ",\n\n" + "These are your new login credentials for E-Procurement Toolkit.\n\n" + "Username: " + person.getUsername() + "\n" + "Password: " + newPassword + "\n\n" + "At login, you will be prompted to change your password to one of your choice.\n\n" + "Thank you,\n" + "DG Team");
    try {
        javaMailSenderImpl.send(msg);
    } catch (MailException e) {
        e.printStackTrace();
    }
}
Also used : SimpleMailMessage(org.springframework.mail.SimpleMailMessage) MailException(org.springframework.mail.MailException)

Example 8 with MailException

use of org.springframework.mail.MailException in project spring-framework by spring-projects.

the class JavaMailSenderImpl method doSend.

/**
	 * Actually send the given array of MimeMessages via JavaMail.
	 * @param mimeMessages MimeMessage objects to send
	 * @param originalMessages corresponding original message objects
	 * that the MimeMessages have been created from (with same array
	 * length and indices as the "mimeMessages" array), if any
	 * @throws org.springframework.mail.MailAuthenticationException
	 * in case of authentication failure
	 * @throws org.springframework.mail.MailSendException
	 * in case of failure when sending a message
	 */
protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException {
    Map<Object, Exception> failedMessages = new LinkedHashMap<>();
    Transport transport = null;
    try {
        for (int i = 0; i < mimeMessages.length; i++) {
            // Check transport connection first...
            if (transport == null || !transport.isConnected()) {
                if (transport != null) {
                    try {
                        transport.close();
                    } catch (Exception ex) {
                    // Ignore - we're reconnecting anyway
                    }
                    transport = null;
                }
                try {
                    transport = connectTransport();
                } catch (AuthenticationFailedException ex) {
                    throw new MailAuthenticationException(ex);
                } catch (Exception ex) {
                    // Effectively, all remaining messages failed...
                    for (int j = i; j < mimeMessages.length; j++) {
                        Object original = (originalMessages != null ? originalMessages[j] : mimeMessages[j]);
                        failedMessages.put(original, ex);
                    }
                    throw new MailSendException("Mail server connection failed", ex, failedMessages);
                }
            }
            // Send message via current transport...
            MimeMessage mimeMessage = mimeMessages[i];
            try {
                if (mimeMessage.getSentDate() == null) {
                    mimeMessage.setSentDate(new Date());
                }
                String messageId = mimeMessage.getMessageID();
                mimeMessage.saveChanges();
                if (messageId != null) {
                    // Preserve explicitly specified message id...
                    mimeMessage.setHeader(HEADER_MESSAGE_ID, messageId);
                }
                transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            } catch (Exception ex) {
                Object original = (originalMessages != null ? originalMessages[i] : mimeMessage);
                failedMessages.put(original, ex);
            }
        }
    } finally {
        try {
            if (transport != null) {
                transport.close();
            }
        } catch (Exception ex) {
            if (!failedMessages.isEmpty()) {
                throw new MailSendException("Failed to close server connection after message failures", ex, failedMessages);
            } else {
                throw new MailSendException("Failed to close server connection after message sending", ex);
            }
        }
    }
    if (!failedMessages.isEmpty()) {
        throw new MailSendException(failedMessages);
    }
}
Also used : MailAuthenticationException(org.springframework.mail.MailAuthenticationException) MailSendException(org.springframework.mail.MailSendException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) MimeMessage(javax.mail.internet.MimeMessage) Transport(javax.mail.Transport) MailParseException(org.springframework.mail.MailParseException) MessagingException(javax.mail.MessagingException) MailAuthenticationException(org.springframework.mail.MailAuthenticationException) MailSendException(org.springframework.mail.MailSendException) AuthenticationFailedException(javax.mail.AuthenticationFailedException) NoSuchProviderException(javax.mail.NoSuchProviderException) MailPreparationException(org.springframework.mail.MailPreparationException) MailException(org.springframework.mail.MailException) Date(java.util.Date) LinkedHashMap(java.util.LinkedHashMap)

Example 9 with MailException

use of org.springframework.mail.MailException in project OpenClinica by OpenClinica.

the class OpenClinicaMailSender method sendEmail.

public void sendEmail(String to, String from, String subject, String body, Boolean htmlEmail) throws OpenClinicaSystemException {
    try {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, htmlEmail);
        helper.setFrom(from);
        helper.setTo(processMultipleImailAddresses(to.trim()));
        helper.setSubject(subject);
        helper.setText(body, true);
        mailSender.send(mimeMessage);
        logger.debug("Email sent successfully on {}", new Date());
    } catch (MailException me) {
        logger.debug("Email could not be sent on {} due to: {}", new Date(), me.toString());
        throw new OpenClinicaSystemException(me.getMessage());
    } catch (MessagingException e) {
        logger.debug("Email could not be sent on {} due to: {}", new Date(), e.toString());
        throw new OpenClinicaSystemException(e.getMessage());
    }
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) MailException(org.springframework.mail.MailException) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper) OpenClinicaSystemException(org.akaza.openclinica.exception.OpenClinicaSystemException) Date(java.util.Date)

Example 10 with MailException

use of org.springframework.mail.MailException in project OpenClinica by OpenClinica.

the class RandomizationRegistrar method sendEmail.

public void sendEmail(JavaMailSenderImpl mailSender, UserAccountBean user, String emailSubject, String message) throws OpenClinicaSystemException {
    logger.info("Sending email...");
    try {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setFrom(EmailEngine.getAdminEmail());
        helper.setTo(user.getEmail());
        helper.setSubject(emailSubject);
        helper.setText(message);
        mailSender.send(mimeMessage);
        logger.debug("Email sent successfully on {}", new Date());
    } catch (MailException me) {
        logger.error("Email could not be sent");
    } catch (MessagingException me) {
        logger.error("Email could not be sent");
    }
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) MailException(org.springframework.mail.MailException) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper) Date(java.util.Date)

Aggregations

MailException (org.springframework.mail.MailException)15 MimeMessage (javax.mail.internet.MimeMessage)11 MimeMessageHelper (org.springframework.mail.javamail.MimeMessageHelper)9 Date (java.util.Date)8 MessagingException (javax.mail.MessagingException)7 SimpleMailMessage (org.springframework.mail.SimpleMailMessage)4 RegistrarException (cz.metacentrum.perun.registrar.exceptions.RegistrarException)3 ApplicationForm (cz.metacentrum.perun.registrar.model.ApplicationForm)3 ApplicationMail (cz.metacentrum.perun.registrar.model.ApplicationMail)3 MailText (cz.metacentrum.perun.registrar.model.ApplicationMail.MailText)3 SQLException (java.sql.SQLException)3 Properties (java.util.Properties)3 OpenClinicaSystemException (org.akaza.openclinica.exception.OpenClinicaSystemException)3 DuplicateKeyException (org.springframework.dao.DuplicateKeyException)3 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)3 JavaMailSenderImpl (org.springframework.mail.javamail.JavaMailSenderImpl)3 Application (cz.metacentrum.perun.registrar.model.Application)2 AuthenticationFailedException (javax.mail.AuthenticationFailedException)2 NoSuchProviderException (javax.mail.NoSuchProviderException)2 MailAuthenticationException (org.springframework.mail.MailAuthenticationException)2