Search in sources :

Example 31 with MailException

use of org.springframework.mail.MailException in project books by aidanwhiteley.

the class MailClient method sendEmailsToAdminsForNewUsers.

public boolean sendEmailsToAdminsForNewUsers(List<User> newUsers) {
    boolean emailSent = true;
    MimeMessagePreparator messagePreparator = mimeMessage -> {
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setFrom(registrationAdminEmailFrom);
        messageHelper.setTo(registrationAdminEmailTo);
        messageHelper.setSubject(registrationAdminEmailTitle);
        messageHelper.setText(prepareAdminNewUsersNotificationEmailContent(newUsers));
    };
    try {
        mailSender.send(messagePreparator);
    } catch (MailException me) {
        emailSent = false;
        LOGGER.error("Failed to send user registration emails for {}", newUsers, me);
    }
    return emailSent;
}
Also used : Value(org.springframework.beans.factory.annotation.Value) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper) List(java.util.List) Logger(org.slf4j.Logger) User(com.aidanwhiteley.books.domain.User) MimeMessagePreparator(org.springframework.mail.javamail.MimeMessagePreparator) Service(org.springframework.stereotype.Service) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) JavaMailSender(org.springframework.mail.javamail.JavaMailSender) MailException(org.springframework.mail.MailException) MimeMessagePreparator(org.springframework.mail.javamail.MimeMessagePreparator) MailException(org.springframework.mail.MailException) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper)

Example 32 with MailException

use of org.springframework.mail.MailException in project webofneeds by researchstudio-sat.

the class WonWebSocketHandler method notifyPerEmail.

private void notifyPerEmail(final User user, final URI atomUri, final WonMessage wonMessage, URI connectionUri) {
    if (wonMessage.getFocalMessage().getMessageType().isResponseMessage()) {
        // we assume that this message, coming from the server here, can only be an
        // echoed message. don't send by email.
        logger.debug("not sending email to user: message {} looks like an echo from the server", wonMessage.getMessageURI());
        return;
    }
    if (user == null) {
        logger.info("not sending email to user: user not specified");
        return;
    }
    if (user.isAnonymous()) {
        logger.debug("not sending email to user: user is anonymous");
        return;
    }
    if (!user.isEmailVerified()) {
        logger.debug("not sending email to user: email address not yet verified");
        return;
    }
    UserAtom userAtom = getAtomOfUser(user, atomUri);
    if (userAtom == null) {
        logger.debug("not sending email to user: atom uri not specified");
        return;
    }
    UserAtom senderAtom = getAtomOfUser(user, wonMessage.getSenderAtomURI());
    if (senderAtom != null) {
        logger.debug("not sending email to user: sender and recipient atoms are controlled by same user.");
        return;
    }
    String textMsg = WonRdfUtils.MessageUtils.getTextMessage(wonMessage);
    try {
        switch(wonMessage.getMessageType()) {
            case CONNECTION_MESSAGE:
                if (userAtom.isConversations()) {
                    emailSender.sendConversationNotificationMessage(user.getEmail(), atomUri.toString(), wonMessage.getSenderAtomURI().toString(), connectionUri.toString(), wonMessage.getRecipientSocketURIRequired().toString(), wonMessage.getSenderSocketURIRequired().toString(), textMsg);
                }
                return;
            case CONNECT:
                if (userAtom.isRequests()) {
                    emailSender.sendConnectNotificationMessage(user.getEmail(), atomUri.toString(), wonMessage.getSenderAtomURI().toString(), connectionUri.toString(), wonMessage.getRecipientSocketURIRequired().toString(), wonMessage.getSenderSocketURIRequired().toString(), textMsg);
                }
                return;
            case ATOM_HINT_MESSAGE:
            case SOCKET_HINT_MESSAGE:
                if (userAtom.isMatches()) {
                    Optional<URI> targetAtomUri = WonLinkedDataUtils.getAtomOfSocket(wonMessage.getHintTargetSocketURI(), linkedDataSource);
                    if (!isConnectionInSuggestedState(connectionUri)) {
                        // found the connection previously and we don't want to notify them
                        return;
                    }
                    if (targetAtomUri.isPresent()) {
                        // user a hash of the user's email address for the key, so as not to hold
                        // users emails in memory all the time
                        MessageDigest digest = MessageDigest.getInstance("SHA-256");
                        byte[] hash = digest.digest(user.getEmail().getBytes(StandardCharsets.UTF_8));
                        String key = "HINT" + Base64.getEncoder().encodeToString(hash);
                        String[] args = new String[] { user.getEmail(), atomUri.toString(), targetAtomUri.get().toString(), connectionUri.toString() };
                        // only count 1 item per atom/atom combination per batch key.
                        String deduplicationKey = atomUri.toString() + targetAtomUri.toString();
                        // set the configuration
                        BatchingConsumer.Config config = new BatchingConsumer.ConfigBuilder().consumeFirst(// send the first mail immediately
                        true).maxBatchAge(// empty batch at least once a day
                        Duration.ofHours(24)).maxItemInterval(// wait 10 minutes after the last
                        Duration.ofMinutes(10)).minChunkInterval(// send at most 1 mail every 6 hours
                        Duration.ofHours(6)).maxBatchSize(// as soon as we reach 50 hints, send mail
                        50).build();
                        batchingConsumer.accept(key, args, deduplicationKey, batch -> {
                            if (batch.size() == 1) {
                                String[] a = batch.iterator().next();
                                emailSender.sendHintNotificationMessage(a[0], a[1], a[2], a[3]);
                            } else if (batch.size() > 0) {
                                String[] a = batch.iterator().next();
                                Map<String, Long> hintCounts = batch.stream().collect(Collectors.groupingBy(item -> item[1], Collectors.counting()));
                                emailSender.sendMultipleHintsNotificationMessage(a[0], hintCounts);
                            }
                        }, config);
                    } else {
                        logger.info("received socket hint to {} but could not identify corresponding atom - no mail sent.", wonMessage.getHintTargetSocketURI());
                    }
                }
                return;
            case CLOSE:
                // do not send emails for a close
                return;
            case DEACTIVATE:
                // a deactivate message, coming from the WoN node. Always deliverd by email.
                emailSender.sendSystemDeactivateNotificationMessage(user.getEmail(), atomUri.toString(), textMsg);
                return;
            case ATOM_MESSAGE:
                // an atom message, coming from the WoN node. Always deliverd by email.
                emailSender.sendAtomMessageNotificationMessage(user.getEmail(), atomUri.toString(), textMsg);
                return;
            default:
                return;
        }
    } catch (MailException | NoSuchAlgorithmException ex) {
        logger.error("Email could not be sent", ex);
    }
}
Also used : BatchingConsumer(won.utils.batch.BatchingConsumer) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) URI(java.net.URI) UserAtom(won.owner.model.UserAtom) MailException(org.springframework.mail.MailException) MessageDigest(java.security.MessageDigest) Map(java.util.Map)

Example 33 with MailException

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

the class NotificationActionProcessor method sendEmail.

private void sendEmail(RuleActionBean ruleAction, ParticipantDTO pDTO) throws OpenClinicaSystemException {
    logger.info("Sending email...");
    try {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setFrom(EmailEngine.getAdminEmail());
        helper.setTo(pDTO.getEmailAccount());
        helper.setSubject(pDTO.getEmailSubject());
        helper.setText(pDTO.getMessage());
        mailSender.send(mimeMessage);
        logger.debug("Email sent successfully on {}", new Date());
    } catch (MailException me) {
        logger.error("Email could not be sent");
        throw new OpenClinicaSystemException(me.getMessage());
    } catch (MessagingException me) {
        logger.error("Email could not be sent");
        throw new OpenClinicaSystemException(me.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 34 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)

Example 35 with MailException

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

the class SecureController method sendEmail.

public Boolean sendEmail(String to, String from, String subject, String body, Boolean htmlEmail, String successMessage, String failMessage, Boolean sendMessage) throws Exception {
    Boolean messageSent = true;
    try {
        JavaMailSenderImpl mailSender = (JavaMailSenderImpl) SpringServletAccess.getApplicationContext(context).getBean("mailSender");
        // @pgawade 09-Feb-2012 #issue 13201 - setting the "mail.smtp.localhost" property to localhost when java API is not able to
        // retrieve the host name
        Properties javaMailProperties = mailSender.getJavaMailProperties();
        if (null != javaMailProperties) {
            if (javaMailProperties.get("mail.smtp.localhost") == null || ((String) javaMailProperties.get("mail.smtp.localhost")).equalsIgnoreCase("")) {
                javaMailProperties.put("mail.smtp.localhost", "localhost");
            }
        }
        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);
        if (successMessage != null && sendMessage) {
            addPageMessage(successMessage);
        }
        logger.debug("Email sent successfully on {}", new Date());
    } catch (MailException me) {
        me.printStackTrace();
        if (failMessage != null && sendMessage) {
            addPageMessage(failMessage);
        }
        logger.debug("Email could not be sent on {} due to: {}", new Date(), me.toString());
        messageSent = false;
    }
    return messageSent;
}
Also used : JavaMailSenderImpl(org.springframework.mail.javamail.JavaMailSenderImpl) MimeMessage(javax.mail.internet.MimeMessage) MailException(org.springframework.mail.MailException) Properties(java.util.Properties) MimeMessageHelper(org.springframework.mail.javamail.MimeMessageHelper) Date(java.util.Date)

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