org.springframework.mail.MailException Java Examples

The following examples show how to use org.springframework.mail.MailException. 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 File: ConfirmationServiceImpl.java    From olat with 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 #2
Source File: MailServiceImpl.java    From olat with 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 #3
Source File: EmailService.java    From jcart with 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 #4
Source File: MailPublisher.java    From logsniffer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #5
Source File: MailChannel.java    From olat with 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 #6
Source File: EmailVerificationHelper.java    From zhcet-web with 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 #7
Source File: MailUserInputProcessor.java    From sshd-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
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 #8
Source File: JavaMailSenderImpl.java    From spring-analysis-note with 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 #9
Source File: SimpleEmailServiceJavaMailSender.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@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 #10
Source File: JavaMailSenderImpl.java    From java-technology-stack with 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 #11
Source File: SimpleEmailServiceJavaMailSender.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: SimpleEmailServiceJavaMailSender.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@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 #13
Source File: SendOrderConfirmationEmailAdvice.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #14
Source File: MailChannel.java    From olat with 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 #15
Source File: MailClientUtils.java    From bamboobsc with 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 #16
Source File: MailClientUtils.java    From bamboobsc with 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 #17
Source File: MailAdapter.java    From ods-provisioning-app with 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 #18
Source File: EmailSupport.java    From OpenCue with 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 #19
Source File: MailServiceConcordionMock.java    From olat with 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 #20
Source File: TestMailSender.java    From haven-platform with 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 File: JavaMailSenderImpl.java    From lams with 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 #22
Source File: JavaMailSenderImpl.java    From lams with 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 #23
Source File: SlaCheckerEmailServiceTest.java    From mojito with 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 #24
Source File: JavaMailSenderImpl.java    From spring4-understanding with 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 #25
Source File: MailServiceConcordionMock.java    From olat with 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 #26
Source File: EmailService.java    From SkaETL with 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 #27
Source File: JavaMailSenderImpl.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public void send(MimeMessagePreparator mimeMessagePreparator) throws MailException {
	send(new MimeMessagePreparator[] {mimeMessagePreparator});
}
 
Example #28
Source File: MailServiceITCaseNew.java    From olat with Apache License 2.0 4 votes vote down vote up
@Override
public void send(SimpleMailMessage message) throws MailException {
    this.lastSendSimpleMessage = message;
}
 
Example #29
Source File: JavaMailSenderImpl.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public void send(SimpleMailMessage simpleMessage) throws MailException {
	send(new SimpleMailMessage[] {simpleMessage});
}
 
Example #30
Source File: MailServiceITCaseNew.java    From olat with Apache License 2.0 4 votes vote down vote up
@Override
public void send(MimeMessage[] arg0) throws MailException {
    // TODO Auto-generated method stub

}