use of cz.metacentrum.perun.notif.mail.exception.EmailAuthenticationException in project perun by CESNET.
the class PerunNotifEmailManagerImpl method doSend.
/**
* Actually send the given array of MimeMessages via JavaMail.
*
* @param mimeMessages MimeMessage objects to send
* @throws EmailAuthenticationException in case of authentication
* failure
* @throws EmailSendException in case of failure when sending a message
*/
protected void doSend(MimeMessage[] mimeMessages, List<String> contents) throws EmailException {
Map<Object, Exception> failedMessages = new LinkedHashMap<Object, Exception>();
Transport transport;
try {
transport = getTransport(getSession());
transport.connect(smtpHost, port, username, password);
} catch (AuthenticationFailedException ex) {
throw new EmailAuthenticationException(ex);
} catch (MessagingException ex) {
// Effectively, all messages failed...
for (int i = 0; i < mimeMessages.length; i++) {
failedMessages.put(mimeMessages[i], ex);
}
throw new EmailSendException("Mail server connection failed", ex, failedMessages);
}
try {
for (int i = 0; i < mimeMessages.length; i++) {
MimeMessage mimeMessage = mimeMessages[i];
String content = contents.get(i);
try {
if (mimeMessage.getSentDate() == null) {
mimeMessage.setSentDate(new Date());
}
mimeMessage.saveChanges();
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
sendMessagesLogger.info("Email sent in {} with receivers: " + Arrays.toString(mimeMessage.getRecipients(Message.RecipientType.TO)) + " senders: " + Arrays.toString(mimeMessage.getFrom()) + " subject: " + mimeMessage.getSubject() + " content: " + content, new Date());
} catch (MessagingException ex) {
try {
logger.error("Error during send of email for: {}", mimeMessage.getRecipients(Message.RecipientType.TO), ex);
} catch (Exception ex2) {
logger.error("Cannot send email.", ex);
}
failedMessages.put(mimeMessage, ex);
}
}
} finally {
try {
transport.close();
} catch (MessagingException ex) {
if (!failedMessages.isEmpty()) {
throw new EmailSendException("Failed to close server connection after message failures", ex, failedMessages);
} else {
throw new EmailSendException("Failed to close server connection after message sending", ex);
}
}
}
if (!failedMessages.isEmpty()) {
throw new EmailSendException(failedMessages);
}
}
Aggregations