Search in sources :

Example 41 with MailException

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

the class MailManagerImpl method mailValidation.

private void mailValidation(Application app, ApplicationMail mail, List<ApplicationFormItemData> data, String reason, List<Exception> exceptions) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();
    // set FROM
    setFromMailAddress(message, app);
    // set TO
    // empty = not sent
    message.setRecipient(Message.RecipientType.TO, null);
    // get language
    Locale lang = new Locale(getLanguageFromAppData(app, data));
    // get localized subject and text
    String mailText = getMailText(mail, lang, app, data, reason, exceptions);
    message.setText(mailText);
    String mailSubject = getMailSubject(mail, lang, app, data, reason, exceptions);
    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
        int loa = 0;
        try {
            loa = Integer.parseInt(d.getAssuranceLevel());
        } catch (NumberFormatException ex) {
        // ignore
        }
        if (ApplicationFormItem.Type.VALIDATED_EMAIL.equals(item.getType()) && loa < 1) {
            if (value != null && !value.isEmpty()) {
                // set TO
                message.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(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 = EMPTY_STRING;
                        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=" + getUrlEncodedString(app.getVo().getShortName());
                                newValue += ((app.getGroup() != null) ? "&group=" + getUrlEncodedString(app.getGroup().getName()) : EMPTY_STRING);
                                newValue += "&i=" + getUrlEncodedString(i) + "&m=" + getUrlEncodedString(m);
                            }
                        }
                        // substitute {validationLink-authz} with actual value or empty string
                        mailText = mailText.replace(toSubstitute, newValue != null ? newValue : EMPTY_STRING);
                    }
                }
                if (mailText.contains(FIELD_VALIDATION_LINK)) {
                    // 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/";
                        url = url + "?vo=" + getUrlEncodedString(app.getVo().getShortName());
                        if (app.getGroup() != null) {
                            // append group name for
                            url += "&group=" + getUrlEncodedString(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("?");
                        }
                        if (!url2.toString().isEmpty())
                            url2.append("i=").append(getUrlEncodedString(i)).append("&m=").append(getUrlEncodedString(m));
                        // replace validation link
                        mailText = mailText.replace(FIELD_VALIDATION_LINK, url2.toString());
                    }
                }
                if (mailText.contains(FIELD_REDIRECT_URL)) {
                    String redirectURL = BeansUtils.stringToMapOfAttributes(app.getFedInfo()).get("redirectURL");
                    mailText = mailText.replace(FIELD_REDIRECT_URL, redirectURL != null ? "&target=" + getUrlEncodedString(redirectURL) : EMPTY_STRING);
                }
                // set replaced text
                message.setText(mailText);
                try {
                    mailSender.send(message);
                    log.info("[MAIL MANAGER] Sending mail: MAIL_VALIDATION to: {} / appID: {} / {} / {}", message.getAllRecipients(), app.getId(), app.getVo(), app.getGroup());
                } 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);
            }
        }
    }
}
Also used : ApplicationFormItem(cz.metacentrum.perun.registrar.model.ApplicationFormItem) Pattern(java.util.regex.Pattern) InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) Matcher(java.util.regex.Matcher) ApplicationFormItemData(cz.metacentrum.perun.registrar.model.ApplicationFormItemData) MailException(org.springframework.mail.MailException)

Example 42 with MailException

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

the class MailManagerImpl method appCreatedVoAdmin.

private void appCreatedVoAdmin(Application app, ApplicationMail mail, List<ApplicationFormItemData> data, String reason, List<Exception> exceptions) throws MessagingException {
    MimeMessage message = getAdminMessage(app, mail, data, reason, exceptions);
    // send a message to all VO or Group admins
    List<String> toEmail = getToMailAddresses(app);
    for (String email : toEmail) {
        setRecipient(message, email);
        try {
            mailSender.send(message);
            log.info("[MAIL MANAGER] Sending mail: APP_CREATED_VO_ADMIN to: {} / appID: {} / {} / {}", message.getAllRecipients(), app.getId(), app.getVo(), app.getGroup());
        } catch (MailException | MessagingException ex) {
            log.error("[MAIL MANAGER] Sending mail: APP_CREATED_VO_ADMIN failed because of exception.", ex);
        }
    }
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) MailException(org.springframework.mail.MailException)

Example 43 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 the 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, @Nullable 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);
                }
                Address[] addresses = mimeMessage.getAllRecipients();
                transport.sendMessage(mimeMessage, (addresses != null ? addresses : new Address[0]));
            } 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) Address(jakarta.mail.Address) AuthenticationFailedException(jakarta.mail.AuthenticationFailedException) MailParseException(org.springframework.mail.MailParseException) NoSuchProviderException(jakarta.mail.NoSuchProviderException) MailAuthenticationException(org.springframework.mail.MailAuthenticationException) MessagingException(jakarta.mail.MessagingException) MailSendException(org.springframework.mail.MailSendException) MailPreparationException(org.springframework.mail.MailPreparationException) MailException(org.springframework.mail.MailException) AuthenticationFailedException(jakarta.mail.AuthenticationFailedException) Date(java.util.Date) LinkedHashMap(java.util.LinkedHashMap) MimeMessage(jakarta.mail.internet.MimeMessage) Transport(jakarta.mail.Transport)

Example 44 with MailException

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

the class Utils method sendEmail.

/**
 * Send message with specific body and subject to the email.
 *
 * @param subjectOfEmail specific subject of mail (need to be not null)
 * @param bodyOfEmail specific text of body of mail (need to be not null)
 * @param email email to send message to (need to be not null)
 */
private static void sendEmail(String subjectOfEmail, String bodyOfEmail, String email) {
    notNull(subjectOfEmail, "subject");
    notNull(bodyOfEmail, "body");
    notNull(email, "email");
    // create mail sender
    JavaMailSender mailSender = BeansUtils.getDefaultMailSender();
    // create message
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(email);
    message.setFrom(BeansUtils.getCoreConfig().getMailchangeBackupFrom());
    // set subject and body
    message.setSubject(subjectOfEmail);
    message.setText(bodyOfEmail);
    // send email
    try {
        mailSender.send(message);
    } catch (MailException ex) {
        log.error("Unable to send email to '" + email + "'.", ex);
        throw new InternalErrorException("Unable to send email.", ex);
    }
}
Also used : SimpleMailMessage(org.springframework.mail.SimpleMailMessage) MailException(org.springframework.mail.MailException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) JavaMailSender(org.springframework.mail.javamail.JavaMailSender)

Example 45 with MailException

use of org.springframework.mail.MailException in project uhgroupings by uhawaii-system-its-ti-iam.

the class EmailService method sendWithStack.

public void sendWithStack(Exception e, String exceptionType) {
    logger.info("Feedback Error email has been triggered.");
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    String exceptionAsString = sw.toString();
    InetAddress ip;
    String hostname = "Unknown Host";
    try {
        ip = InetAddress.getLocalHost();
        hostname = ip.getHostName();
    } catch (UnknownHostException f) {
        f.printStackTrace();
    }
    if (isEnabled) {
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setTo(to);
        msg.setFrom(from);
        String text = "";
        String header = "UH Groupings UI Error Response";
        text += "Cause of Response: The UI threw an exception that has triggered the ErrorControllerAdvice. \n\n";
        text += "Exception Thrown: ErrorControllerAdvice threw the " + exceptionType + ".\n\n";
        text += "Host Name: " + hostname + ".\n";
        text += "----------------------------------------------------" + "\n\n";
        text += "UI Stack Trace: \n\n" + exceptionAsString;
        msg.setText(text);
        msg.setSubject(header);
        try {
            javaMailSender.send(msg);
        } catch (MailException ex) {
            logger.error("Error", ex);
        }
    }
}
Also used : StringWriter(java.io.StringWriter) UnknownHostException(java.net.UnknownHostException) SimpleMailMessage(org.springframework.mail.SimpleMailMessage) MailException(org.springframework.mail.MailException) InetAddress(java.net.InetAddress) PrintWriter(java.io.PrintWriter)

Aggregations

MailException (org.springframework.mail.MailException)47 MimeMessage (javax.mail.internet.MimeMessage)18 SimpleMailMessage (org.springframework.mail.SimpleMailMessage)17 MimeMessageHelper (org.springframework.mail.javamail.MimeMessageHelper)15 MessagingException (javax.mail.MessagingException)10 Date (java.util.Date)8 Properties (java.util.Properties)3 InternetAddress (javax.mail.internet.InternetAddress)3 OpenClinicaSystemException (org.akaza.openclinica.exception.OpenClinicaSystemException)3 JavaMailSender (org.springframework.mail.javamail.JavaMailSender)3 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)2 AuthenticationFailedException (jakarta.mail.AuthenticationFailedException)2 MessagingException (jakarta.mail.MessagingException)2 NoSuchProviderException (jakarta.mail.NoSuchProviderException)2 MimeMessage (jakarta.mail.internet.MimeMessage)2 PrintWriter (java.io.PrintWriter)2 URI (java.net.URI)2 Matcher (java.util.regex.Matcher)2 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)2 MolgenisDataException (org.molgenis.data.MolgenisDataException)2