Java Code Examples for org.springframework.mail.MailException

The following examples show how to use org.springframework.mail.MailException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: olat   Source File: MailChannel.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @Retryable since it could throw a MailException if the sendMailWithTemplate fails, so we might want to retry. <br/>
 *            However, if an "Invalid Addresses" is the reason for the failure, is useless to retry, <br/>
 *            so we throw a new exception (InvalidAddressException) which is not catched by the TransactionRetryer.
 */
@Retryable
public void send(Subscriber subscriber, List<NotificationEventTO> events) throws Exception {
    String emailAddress = subscriber.getIdentity().getAttributes().getEmail();
    try {
        mailService.sendMailWithTemplate(emailBuilder.getTemplateMailTO(emailAddress, events));
    } catch (MailException e) {
        String message = e.getMessage();
        if (message != null && !message.isEmpty() && message.indexOf("Invalid Addresses") > 0) {
            // bypass the retry
            log.error("Invalid Addresses detected !!! ", e);
            throw new InvalidAddressException(e, emailAddress);
        }
        throw e;
    }
}
 
Example 2
Source Project: zhcet-web   Source File: EmailVerificationHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends mail to the user to be verified and saves the user with the email and status to be unverified
 * Also, publishes an event notifying the same
 * @param token {@link VerificationToken} token to be sent email with respect to
 */
@Async
public void sendMail(VerificationToken token) {
    String relativeUrl = "/login/email/verify?auth=" + token.getToken();
    log.debug("Verification link generated : {}", relativeUrl);

    try {
        linkMailService.sendEmail(getPayLoad(token.getEmail(), token.getUser(), relativeUrl), false);
        // Now we set the email to the user and disable email verified
        User user = token.getUser();
        log.debug("Saving user email {} -> {}", user.getUserId(), token.getEmail());
        user.setEmail(token.getEmail());
        user.setEmailVerified(false);

        userService.save(user);
        log.debug("Saved user email");
        eventPublisher.publishEvent(new EmailVerifiedEvent(user));
    } catch (MailException mailException) {
        // There was an error sending the mail, so remove the token and sent time
        verificationTokenRepository.delete(token);
        emailCache.invalidate(token.getUser().getUserId());
        log.warn("Email sending for {} '{}' failed, so we removed the verification token",
                token.getUser(), token.getEmail(), mailException);
    }
}
 
Example 3
Source Project: olat   Source File: MailServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void sendMailWithTemplate(final TemplateMailTO mailParameters) throws MailException {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);

            message.setTo(mailParameters.getToMailAddress());
            message.setFrom(mailParameters.getFromMailAddress());
            message.setSubject(mailParameters.getSubject());
            if (mailParameters.hasCcMailAddress()) {
                message.setCc(mailParameters.getCcMailAddress());
            }
            if (mailParameters.hasReplyTo()) {
                message.setReplyTo(mailParameters.getReplyTo());
            }
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, mailParameters.getTemplateLocation(), mailParameters.getTemplateProperties());
            log.debug("*** TEST text='" + text + "'");
            message.setText(text, true);
            message.setValidateAddresses(true);

        }
    };
    this.mailSender.send(preparator);
}
 
Example 4
Source Project: olat   Source File: ConfirmationServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private boolean sendToOneRecipient(MailMessage messageClone, String toEmailAddress) {
    boolean delivered = false;
    try {
        LOG.info("send message to: " + toEmailAddress);
        mailService.sendMailWithAttachments(emailBuilder.getMailTemplate(toEmailAddress, messageClone));
        delivered = true;
    } catch (MailException ex) {
        String exMessage = ex.getMessage();
        if (messageClone != null && !exMessage.isEmpty() && exMessage.indexOf("Invalid Addresses") > 0) {
            delivered = false;
            // bypass the retry and log the invalid address - but send for the next recipient
            LOG.error("Invalid Addresses detected !!! " + toEmailAddress, ex);
        } else {
            // retry, if no Invalid Addresses
            throw ex;
        }
    } finally {
        notifyMetrics(delivered);
    }
    return delivered;
}
 
Example 5
@Override
public void publish(final Event event) throws PublishException {
	try {
		final VelocityContext context = velocityRenderer.getContext(event);
		final SimpleMailMessage email = new SimpleMailMessage();
		email.setFrom(getFrom());
		email.setSubject(velocityRenderer.render(getSubject(), context));
		email.setText(velocityRenderer.render(getTextMessage(), context) + " ");
		final String to2 = getTo();
		email.setTo(to2.split(",|\\s"));
		mailSender.send(email);
		logger.info("Sent event notification to: {}", to2);
	} catch (final MailException e) {
		throw new PublishException("Failed to send event notification to mail: " + getTo(), e);
	}
}
 
Example 6
Source Project: jcart   Source File: EmailService.java    License: MIT License 6 votes vote down vote up
public void sendEmail(String to, String subject, String content)
{
       try
	{
       	// Prepare message using a Spring helper
           final MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
           final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
           message.setSubject(subject);
           message.setFrom(supportEmail);
           message.setTo(to);
           message.setText(content, true /* isHtml */);
           
		javaMailSender.send(message.getMimeMessage());
	} 
       catch (MailException | MessagingException e)
	{
       	logger.error(e);
		throw new JCartException("Unable to send email");
	}
}
 
Example 7
Source Project: spring-analysis-note   Source File: JavaMailSenderImpl.java    License: MIT License 5 votes vote down vote up
@Override
public MimeMessage createMimeMessage(InputStream contentStream) throws MailException {
	try {
		return new MimeMessage(getSession(), contentStream);
	}
	catch (Exception ex) {
		throw new MailParseException("Could not parse raw MIME content", ex);
	}
}
 
Example 8
@Override
public MimeMessage createMimeMessage(InputStream contentStream) throws MailException {
	try {
		return new MimeMessage(getSession(), contentStream);
	}
	catch (MessagingException e) {
		throw new MailParseException("Could not parse raw MIME content", e);
	}
}
 
Example 9
Source Project: java-technology-stack   Source File: JavaMailSenderImpl.java    License: MIT License 5 votes vote down vote up
@Override
public MimeMessage createMimeMessage(InputStream contentStream) throws MailException {
	try {
		return new MimeMessage(getSession(), contentStream);
	}
	catch (Exception ex) {
		throw new MailParseException("Could not parse raw MIME content", ex);
	}
}
 
Example 10
@SuppressWarnings("OverloadedVarargsMethod")
@Override
public void send(MimeMessagePreparator... mimeMessagePreparators)
		throws MailException {
	MimeMessage mimeMessage = createMimeMessage();
	for (MimeMessagePreparator mimeMessagePreparator : mimeMessagePreparators) {
		try {
			mimeMessagePreparator.prepare(mimeMessage);
		}
		catch (Exception e) {
			throw new MailPreparationException(e);
		}
	}
	send(mimeMessage);
}
 
Example 11
Source Project: SkaETL   Source File: EmailService.java    License: Apache License 2.0 5 votes vote down vote up
public void send(String destination, String subject, String message) throws MailException {

        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setFrom("[email protected]");
        msg.setTo(destination);
        msg.setSubject(subject);
        msg.setText(message);

        emailSender.send(msg);
    }
 
Example 12
Source Project: ods-provisioning-app   Source File: MailAdapter.java    License: Apache License 2.0 5 votes vote down vote up
public void notifyUsersAboutProject(OpenProjectData data) {
  if (!isMailEnabled) {
    logger.debug("Do not send email, because property mail.enabled is set to false.");
    return;
  }
  String recipient = manager.getUserEmail();
  MimeMessagePreparator messagePreparator =
      mimeMessage -> {
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setFrom(mailSenderAddress);
        messageHelper.setTo(recipient);
        messageHelper.setSubject("ODS Project provision update");
        messageHelper.setText(build(data), true);
      };

  Thread sendThread =
      new Thread(
          () -> {
            try {
              MDC.put(STR_LOGFILE_KEY, data.projectKey);
              mailSender.send(messagePreparator);
            } catch (MailException e) {
              logger.error("Error in sending mail for project: " + data.projectKey, e);
            } finally {
              MDC.remove(STR_LOGFILE_KEY);
            }
          });

  sendThread.start();
  logger.debug("Mail for project: {} sent", data.projectKey);
}
 
Example 13
Source Project: OpenCue   Source File: EmailSupport.java    License: Apache License 2.0 5 votes vote down vote up
public void sendMessage(SimpleMailMessage message) {
    try {
        mailSender.send(message);
    } catch (MailException ex) {
        logger.warn("Failed to send launch failure email, " + ex.getMessage());
    }
}
 
Example 14
Source Project: lams   Source File: JavaMailSenderImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void send(SimpleMailMessage... simpleMessages) throws MailException {
	List<MimeMessage> mimeMessages = new ArrayList<MimeMessage>(simpleMessages.length);
	for (SimpleMailMessage simpleMessage : simpleMessages) {
		MimeMailMessage message = new MimeMailMessage(createMimeMessage());
		simpleMessage.copyTo(message);
		mimeMessages.add(message.getMimeMessage());
	}
	doSend(mimeMessages.toArray(new MimeMessage[mimeMessages.size()]), simpleMessages);
}
 
Example 15
Source Project: lams   Source File: JavaMailSenderImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public MimeMessage createMimeMessage(InputStream contentStream) throws MailException {
	try {
		return new MimeMessage(getSession(), contentStream);
	}
	catch (Exception ex) {
		throw new MailParseException("Could not parse raw MIME content", ex);
	}
}
 
Example 16
Source Project: olat   Source File: MailServiceConcordionMock.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sendMailWithTemplate(final TemplateMailTO mailParameters) throws MailException {

    String emailBody = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, mailParameters.getTemplateLocation(), mailParameters.getTemplateProperties());
    userStatisticMap.put(getUserNameFromEmailAddress(mailParameters.getToMailAddress()), new UserNotifyStatistic(mailParameters.getToMailAddress(), true, emailBody,
            mailParameters.getSubject(), mailParameters.getFromMailAddress()));

}
 
Example 17
private void sendMail(String emailId, String commandExecution, String output) {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
    try {
        helper.setTo(emailId);
        helper.setSubject(commandExecution);
        helper.setText(output);
        mailSender.send(mimeMessage);
        ConsoleIO.writeOutput("Output response sent to " + emailId);
    } catch (MessagingException | MailException ex) {
        ConsoleIO.writeOutput("Error sending mail, please check logs for more info");
        log.error("Error sending mail", ex);
    }
}
 
Example 18
Source Project: spring4-understanding   Source File: JavaMailSenderImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void send(SimpleMailMessage... simpleMessages) throws MailException {
	List<MimeMessage> mimeMessages = new ArrayList<MimeMessage>(simpleMessages.length);
	for (SimpleMailMessage simpleMessage : simpleMessages) {
		MimeMailMessage message = new MimeMailMessage(createMimeMessage());
		simpleMessage.copyTo(message);
		mimeMessages.add(message.getMimeMessage());
	}
	doSend(mimeMessages.toArray(new MimeMessage[mimeMessages.size()]), simpleMessages);
}
 
Example 19
Source Project: mojito   Source File: SlaCheckerEmailServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSendEmailError() throws MessagingException, IOException {
    long incidentId = 0L;
    String message = "some message";

    MailException mailException = mock(MailException.class);
    doThrow(mailException).when(emailSender).send(any(MimeMessage.class));

    SlaCheckerEmailService.logger = mock(Logger.class);

    slaCheckerEmailService.sendEmail(incidentId, message);

    verify(SlaCheckerEmailService.logger).error("Can't send OOSLA email", mailException);
}
 
Example 20
Source Project: haven-platform   Source File: TestMailSender.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void send(SimpleMailMessage msg) throws MailException {
    String[] tos = msg.getTo();
    for(String to: tos) {
        mailbox.computeIfAbsent(to, (k) -> new CopyOnWriteArrayList<>()).add(msg);
        log.info("Receive for {}, \n message: {} ", to, msg);
    }
}
 
Example 21
Source Project: olat   Source File: MailServiceConcordionMock.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sendMailWithTemplate(final TemplateMailTO mailParameters) throws MailException {

    String emailBody = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, mailParameters.getTemplateLocation(), mailParameters.getTemplateProperties());
    userStatisticMap.put(getUserNameFromEmailAddress(mailParameters.getToMailAddress()), new UserNotifyStatistic(mailParameters.getToMailAddress(), true, emailBody,
            mailParameters.getSubject(), mailParameters.getFromMailAddress()));

}
 
Example 22
Source Project: bamboobsc   Source File: MailClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void send(
		String from, String to, 
		String cc, String bcc, 
		String subject, String text) throws MailException, Exception {
	
	String mailCc[] = null;
	String mailBcc[] = null;
	if (!StringUtils.isBlank(cc)) {
		mailCc = cc.split(Constants.ID_DELIMITER);
	}
	if (!StringUtils.isBlank(bcc)) {
		mailBcc = bcc.split(Constants.ID_DELIMITER);
	}
	send(from, to, mailCc, mailBcc, subject, text);
}
 
Example 23
Source Project: bamboobsc   Source File: MailClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void send(
		String from, String to, 
		String cc[], String bcc[], 
		String fileNames[], File files[],
		String subject, String text) throws MailException, Exception {
	
	if (mailSender==null) {
		throw new Exception("null mailSender!");
	}
	if (StringUtils.isBlank(from) || StringUtils.isBlank(to)) {
		throw new Exception("from and to is required!");
	}
	if (fileNames!=null && files!=null) {
		if (fileNames.length != files.length) {
			throw new Exception("File parameter error!");
		}
	}
	MimeMessage message = mailSender.createMimeMessage();
	MimeMessageHelper helper = new MimeMessageHelper(message, true, Constants.BASE_ENCODING);
	helper.setFrom(from);
	helper.setTo( to.endsWith(";") ? to.substring(0, to.length()-1) : to );
	helper.setSubject(subject);
	helper.setText(text, true);
	if (null!=cc && cc.length>0) {
		helper.setCc(cc);
	}
	if (null!=bcc && bcc.length>0) {
		helper.setBcc(bcc);
	}
	for (int i=0; fileNames!=null && i<fileNames.length; i++) {
		helper.addAttachment(fileNames[i], files[i]);
	}
	mailSender.send(message);
}
 
Example 24
public void afterReturning(Object returnValue, Method m, Object[] args, Object target) throws Throwable {
	Order order = (Order) args[0];
	Account account = ((PetStoreFacade) target).getAccount(order.getUsername());

	// don't do anything if email address is not set
	if (account.getEmail() == null || account.getEmail().length() == 0) {
		return;
	}

	StringBuffer text = new StringBuffer();
	text.append("Dear ").append(account.getFirstName()).append(' ').append(account.getLastName());
	text.append(", thank your for your order from JPetStore. Please note that your order number is ");
	text.append(order.getOrderId());

	SimpleMailMessage mailMessage = new SimpleMailMessage();
	mailMessage.setTo(account.getEmail());
	mailMessage.setFrom(this.mailFrom);
	mailMessage.setSubject(this.subject);
	mailMessage.setText(text.toString());
	try {
		this.mailSender.send(mailMessage);
	}
	catch (MailException ex) {
		// just log it and go on
		logger.warn("An exception occured when trying to send email", ex);
	}
}
 
Example 25
@SuppressWarnings("OverloadedVarargsMethod")
@Override
public void send(MimeMessage... mimeMessages) throws MailException {
	Map<Object, Exception> failedMessages = new HashMap<>();

	for (MimeMessage mimeMessage : mimeMessages) {
		try {
			RawMessage rm = createRawMessage(mimeMessage);
			SendRawEmailResult sendRawEmailResult = getEmailService()
					.sendRawEmail(new SendRawEmailRequest(rm));
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("Message with id: {} successfully send",
						sendRawEmailResult.getMessageId());
			}
			mimeMessage.setHeader("Message-ID", sendRawEmailResult.getMessageId());
		}
		catch (Exception e) {
			// Ignore Exception because we are collecting and throwing all if any
			// noinspection ThrowableResultOfMethodCallIgnored
			failedMessages.put(mimeMessage, e);
		}
	}

	if (!failedMessages.isEmpty()) {
		throw new MailSendException(failedMessages);
	}
}
 
Example 26
Source Project: olat   Source File: MailChannel.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @Retryable since it could throw a MailException if the sendMailWithTemplate fails, so we might want to retry. <br/>
 *            However, if an "Invalid Addresses" is the reason for the failure, is useless to retry, <br/>
 *            so we throw a new exception (InvalidAddressException) which is not catched by the TransactionRetryer.
 */
@Retryable
public void send(Subscriber subscriber, List<NotificationEventTO> events) throws Exception {
    try {
        mailService.sendMailWithTemplate(emailBuilder.getTemplateMailTO(subscriber.getIdentity().getAttributes().getEmail(), events));
    } catch (MailException e) {
        String message = e.getMessage();
        if (message != null && !message.isEmpty() && message.indexOf("Invalid Addresses") > 0) {
            // bypass the retry
            log.error("Invalid Addresses detected !!!", e);
            throw new InvalidAddressException(e);
        }
        throw e;
    }
}
 
Example 27
Source Project: spring-analysis-note   Source File: JavaMailSenderImpl.java    License: MIT License 4 votes vote down vote up
@Override
public void send(SimpleMailMessage simpleMessage) throws MailException {
	send(new SimpleMailMessage[] {simpleMessage});
}
 
Example 28
Source Project: olat   Source File: MailServiceITCaseNew.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public MimeMessage createMimeMessage(InputStream arg0) throws MailException {
    // TODO Auto-generated method stub
    return null;
}
 
Example 29
Source Project: spring-analysis-note   Source File: JavaMailSenderImpl.java    License: MIT License 4 votes vote down vote up
@Override
public void send(MimeMessage mimeMessage) throws MailException {
	send(new MimeMessage[] {mimeMessage});
}
 
Example 30
Source Project: spring-analysis-note   Source File: JavaMailSenderImpl.java    License: MIT License 4 votes vote down vote up
@Override
public void send(MimeMessage... mimeMessages) throws MailException {
	doSend(mimeMessages, null);
}