use of org.springframework.mail.MailException in project perun by CESNET.
the class MailManagerImpl method sendMessage.
@Override
public void sendMessage(Application app, MailType mailType, String reason, List<Exception> exceptions) {
try {
// get form
ApplicationForm form;
if (app.getGroup() != null) {
form = registrarManager.getFormForGroup(app.getGroup());
} else {
form = registrarManager.getFormForVo(app.getVo());
}
// get mail definition
ApplicationMail mail = getMailByParams(form.getId(), app.getType(), mailType);
if (mail == null) {
log.error("[MAIL MANAGER] Mail not sent. Definition (or mail text) for: {} do not exists for VO: " + app.getVo() + " and Group: " + app.getGroup(), mailType.toString());
// mail not found
return;
} else if (mail.getSend() == false) {
log.info("[MAIL MANAGER] Mail not sent. Disabled by VO admin for: " + mail.getMailType() + " / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup());
// sending this mail is disabled by VO admin
return;
}
// get app data
List<ApplicationFormItemData> data = registrarManager.getApplicationDataById(registrarSession, app.getId());
// get language
Locale lang = new Locale(getLanguageFromAppData(app, data));
// get localized subject and text
MailText mt = mail.getMessage(lang);
String mailText = "";
String mailSubject = "";
if (mt.getText() != null && !mt.getText().isEmpty()) {
mailText = mt.getText();
}
if (mt.getSubject() != null && !mt.getSubject().isEmpty()) {
mailSubject = mt.getSubject();
}
// different behavior based on mail type
MailType type = mail.getMailType();
if (MailType.APP_CREATED_USER.equals(type)) {
SimpleMailMessage message = new SimpleMailMessage();
// set FROM
setFromMailAddress(message, app);
// set TO
setUsersMailAsTo(message, app, data);
// substitute common strings
mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
// set subject and text
message.setSubject(mailSubject);
message.setText(mailText);
try {
// send mail
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: APP_CREATED_USER to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: APP_CREATED_USER failed because of exception: {}", ex);
}
} else if (MailType.APP_CREATED_VO_ADMIN.equals(type)) {
SimpleMailMessage message = new SimpleMailMessage();
// set FROM
setFromMailAddress(message, app);
// set language independent on user's preferred language.
lang = new Locale("en");
try {
if (app.getGroup() == null) {
// VO
Attribute a = attrManager.getAttribute(registrarSession, app.getVo(), URN_VO_LANGUAGE_EMAIL);
if (a != null && a.getValue() != null) {
lang = new Locale(BeansUtils.attributeValueToString(a));
}
} else {
Attribute a = attrManager.getAttribute(registrarSession, app.getGroup(), URN_GROUP_LANGUAGE_EMAIL);
if (a != null && a.getValue() != null) {
lang = new Locale(BeansUtils.attributeValueToString(a));
}
}
} catch (Exception ex) {
log.error("Error when resolving notification default language: {}", ex);
}
MailText mt2 = mail.getMessage(lang);
String mailText2 = "";
String mailSubject2 = "";
if (mt2.getText() != null && !mt2.getText().isEmpty()) {
mailText2 = mt2.getText();
}
if (mt2.getSubject() != null && !mt2.getSubject().isEmpty()) {
mailSubject2 = mt2.getSubject();
}
// substitute common strings
mailText2 = substituteCommonStrings(app, data, mailText2, reason, exceptions);
mailSubject2 = substituteCommonStrings(app, data, mailSubject2, reason, exceptions);
// set subject and text
message.setSubject(mailSubject2);
message.setText(mailText2);
// send message to all VO or Group admins
List<String> toEmail = getToMailAddresses(app);
for (String email : toEmail) {
message.setTo(email);
try {
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: APP_CREATED_VO_ADMIN to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: APP_CREATED_VO_ADMIN failed because of exception: {}", ex);
}
}
} else if (MailType.MAIL_VALIDATION.equals(type)) {
SimpleMailMessage message = new SimpleMailMessage();
// set FROM
setFromMailAddress(message, app);
// set TO
// empty = not sent
message.setTo("");
// substitute common strings
mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
// set subject and text
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
if (ApplicationFormItem.Type.VALIDATED_EMAIL.equals(item.getType()) && !"1".equals(d.getAssuranceLevel())) {
if (value != null && !value.isEmpty()) {
// set TO
message.setTo(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 = "";
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=" + getEncodedString(app.getVo().getShortName());
newValue += ((app.getGroup() != null) ? "&group=" + getEncodedString(app.getGroup().getName()) : "");
try {
newValue += "&i=" + URLEncoder.encode(i, "UTF-8") + "&m=" + URLEncoder.encode(m, "UTF-8");
} catch (UnsupportedEncodingException ex) {
newValue += "&i=" + i + "&m=" + m;
}
}
}
// substitute {validationLink-authz} with actual value or empty string
mailText = mailText.replace(toSubstitute, newValue);
}
}
if (mailText.contains("{validationLink}")) {
// 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/";
}
if (url != null && !url.isEmpty())
url = url + "?vo=" + getEncodedString(app.getVo().getShortName());
if (app.getGroup() != null) {
// append group name for
if (url != null && !url.isEmpty())
url += "&group=" + getEncodedString(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("?");
}
try {
if (!url2.toString().isEmpty())
url2.append("i=").append(URLEncoder.encode(i, "UTF-8")).append("&m=").append(URLEncoder.encode(m, "UTF-8"));
} catch (UnsupportedEncodingException ex) {
if (!url2.toString().isEmpty())
url2.append("i=").append(i).append("&m=").append(m);
}
// replace validation link
mailText = mailText.replace("{validationLink}", url2.toString());
}
// set replaced text
message.setText(mailText);
try {
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: MAIL_VALIDATION to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} 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);
}
}
}
} else if (type.equals(MailType.APP_APPROVED_USER)) {
SimpleMailMessage message = new SimpleMailMessage();
// set FROM
setFromMailAddress(message, app);
// set TO
setUsersMailAsTo(message, app, data);
// substitute common strings
mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
// set subject and text
message.setSubject(mailSubject);
message.setText(mailText);
try {
// send mail
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: APP_APPROVED_USER to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: APP_APPROVED_USER failed because of exception: {}", ex);
}
} else if (type.equals(MailType.APP_REJECTED_USER)) {
SimpleMailMessage message = new SimpleMailMessage();
// set FROM
setFromMailAddress(message, app);
// set TO
setUsersMailAsTo(message, app, data);
// substitute common strings
mailText = substituteCommonStrings(app, data, mailText, reason, exceptions);
mailSubject = substituteCommonStrings(app, data, mailSubject, reason, exceptions);
// set subject and text
message.setSubject(mailSubject);
message.setText(mailText);
try {
// send mail
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: APP_REJECTED_USER to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: APP_REJECTED_USER failed because of exception: {}", ex);
}
} else if (MailType.APP_ERROR_VO_ADMIN.equals(type)) {
SimpleMailMessage message = new SimpleMailMessage();
// set FROM
setFromMailAddress(message, app);
// set language independent on user's preferred language.
lang = new Locale("en");
try {
if (app.getGroup() == null) {
// VO
Attribute a = attrManager.getAttribute(registrarSession, app.getVo(), URN_VO_LANGUAGE_EMAIL);
if (a != null && a.getValue() != null) {
lang = new Locale(BeansUtils.attributeValueToString(a));
}
} else {
Attribute a = attrManager.getAttribute(registrarSession, app.getGroup(), URN_GROUP_LANGUAGE_EMAIL);
if (a != null && a.getValue() != null) {
lang = new Locale(BeansUtils.attributeValueToString(a));
}
}
} catch (Exception ex) {
log.error("Error when resolving notification default language: {}", ex);
}
MailText mt2 = mail.getMessage(lang);
String mailText2 = "";
String mailSubject2 = "";
if (mt2.getText() != null && !mt2.getText().isEmpty()) {
mailText2 = mt2.getText();
}
if (mt2.getSubject() != null && !mt2.getSubject().isEmpty()) {
mailSubject2 = mt2.getSubject();
}
// substitute common strings
mailText2 = substituteCommonStrings(app, data, mailText2, reason, exceptions);
mailSubject2 = substituteCommonStrings(app, data, mailSubject2, reason, exceptions);
// set subject and text
message.setSubject(mailSubject2);
message.setText(mailText2);
// send message to all VO or Group admins
List<String> toEmail = getToMailAddresses(app);
for (String email : toEmail) {
message.setTo(email);
try {
mailSender.send(message);
log.info("[MAIL MANAGER] Sending mail: APP_ERROR_VO_ADMIN to: {} / appID: " + app.getId() + " / " + app.getVo() + " / " + app.getGroup(), message.getTo());
} catch (MailException ex) {
log.error("[MAIL MANAGER] Sending mail: APP_ERROR_VO_ADMIN failed because of exception: {}", ex);
}
}
} else {
log.error("[MAIL MANAGER] Sending mail type: {} is not supported.", type);
}
} catch (Exception ex) {
// all exceptions are catched and logged to: perun-registrar.log
log.error("[MAIL MANAGER] Exception thrown when sending email: {}", ex);
}
}
use of org.springframework.mail.MailException in project ocvn by devgateway.
the class SendEmailService method sendEmailResetPassword.
/**
* Send a reset password email. This is UNSAFE because passwords are sent in clear text.
* Nevertheless some customers will ask for these emails to be sent, so ...
* @param person
* @param newPassword
*/
public void sendEmailResetPassword(final Person person, final String newPassword) {
SimpleMailMessage msg = new SimpleMailMessage();
msg.setTo(person.getEmail());
msg.setFrom("support@developmentgateway.org");
msg.setSubject("Recover your password");
msg.setText("Dear " + person.getFirstName() + " " + person.getLastName() + ",\n\n" + "These are your new login credentials for E-Procurement Toolkit.\n\n" + "Username: " + person.getUsername() + "\n" + "Password: " + newPassword + "\n\n" + "At login, you will be prompted to change your password to one of your choice.\n\n" + "Thank you,\n" + "DG Team");
try {
javaMailSenderImpl.send(msg);
} catch (MailException e) {
e.printStackTrace();
}
}
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 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, 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);
}
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
} 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);
}
}
use of org.springframework.mail.MailException in project OpenClinica by OpenClinica.
the class OpenClinicaMailSender method sendEmail.
public void sendEmail(String to, String from, String subject, String body, Boolean htmlEmail) throws OpenClinicaSystemException {
try {
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);
logger.debug("Email sent successfully on {}", new Date());
} catch (MailException me) {
logger.debug("Email could not be sent on {} due to: {}", new Date(), me.toString());
throw new OpenClinicaSystemException(me.getMessage());
} catch (MessagingException e) {
logger.debug("Email could not be sent on {} due to: {}", new Date(), e.toString());
throw new OpenClinicaSystemException(e.getMessage());
}
}
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");
}
}
Aggregations