use of org.apache.commons.mail.HtmlEmail in project AuthMeReloaded by AuthMe.
the class SendMailSslTest method shouldCreateEmailObjectWithOAuth2.
@Test
public void shouldCreateEmailObjectWithOAuth2() throws EmailException {
// given
given(settings.getProperty(EmailSettings.SMTP_PORT)).willReturn(587);
given(settings.getProperty(EmailSettings.OAUTH2_TOKEN)).willReturn("oAuth2 token");
String smtpHost = "mail.example.com";
given(settings.getProperty(EmailSettings.SMTP_HOST)).willReturn(smtpHost);
String senderMail = "sender@example.org";
given(settings.getProperty(EmailSettings.MAIL_ACCOUNT)).willReturn(senderMail);
// when
HtmlEmail email = sendMailSsl.initializeMail("recipient@example.com");
// then
assertThat(email, not(nullValue()));
assertThat(email.getToAddresses(), hasSize(1));
assertThat(email.getToAddresses().get(0).getAddress(), equalTo("recipient@example.com"));
assertThat(email.getFromAddress().getAddress(), equalTo(senderMail));
assertThat(email.getHostName(), equalTo(smtpHost));
assertThat(email.getSmtpPort(), equalTo("587"));
Properties mailProperties = email.getMailSession().getProperties();
assertThat(mailProperties.getProperty("mail.smtp.auth.mechanisms"), equalTo("XOAUTH2"));
assertThat(mailProperties.getProperty("mail.smtp.auth.plain.disable"), equalTo("true"));
assertThat(mailProperties.getProperty(OAuth2SaslClientFactory.OAUTH_TOKEN_PROP), equalTo("oAuth2 token"));
}
use of org.apache.commons.mail.HtmlEmail in project AuthMeReloaded by AuthMe.
the class EmailServiceTest method shouldSendPasswordMail.
@Test
public void shouldSendPasswordMail() throws EmailException {
// given
given(settings.getPasswordEmailMessage()).willReturn("Hi <playername />, your new password for <servername /> is <generatedpass />");
given(settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)).willReturn(false);
HtmlEmail email = mock(HtmlEmail.class);
given(sendMailSsl.initializeMail(anyString())).willReturn(email);
given(sendMailSsl.sendEmail(anyString(), eq(email))).willReturn(true);
// when
boolean result = emailService.sendPasswordMail("Player", "user@example.com", "new_password");
// then
assertThat(result, equalTo(true));
verify(sendMailSsl).initializeMail("user@example.com");
ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class);
verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email));
assertThat(messageCaptor.getValue(), equalTo("Hi Player, your new password for serverName is new_password"));
}
use of org.apache.commons.mail.HtmlEmail in project AuthMeReloaded by AuthMe.
the class EmailServiceTest method shouldSendRecoveryCode.
@Test
public void shouldSendRecoveryCode() throws EmailException {
// given
given(settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID)).willReturn(7);
given(settings.getRecoveryCodeEmailMessage()).willReturn("Hi <playername />, your code on <servername /> is <recoverycode /> (valid <hoursvalid /> hours)");
HtmlEmail email = mock(HtmlEmail.class);
given(sendMailSsl.initializeMail(anyString())).willReturn(email);
given(sendMailSsl.sendEmail(anyString(), any(HtmlEmail.class))).willReturn(true);
// when
boolean result = emailService.sendRecoveryCode("Timmy", "tim@example.com", "12C56A");
// then
assertThat(result, equalTo(true));
verify(sendMailSsl).initializeMail("tim@example.com");
ArgumentCaptor<String> messageCaptor = ArgumentCaptor.forClass(String.class);
verify(sendMailSsl).sendEmail(messageCaptor.capture(), eq(email));
assertThat(messageCaptor.getValue(), equalTo("Hi Timmy, your code on serverName is 12C56A (valid 7 hours)"));
}
use of org.apache.commons.mail.HtmlEmail in project dhis2-core by dhis2.
the class EmailMessageSender method sendMessage.
// -------------------------------------------------------------------------
// MessageSender implementation
// -------------------------------------------------------------------------
@Override
public OutboundMessageResponse sendMessage(String subject, String text, String footer, User sender, Set<User> users, boolean forceSend) {
EmailConfiguration emailConfig = getEmailConfiguration();
OutboundMessageResponse status = new OutboundMessageResponse();
String errorMessage = "No recipient found";
if (emailConfig.getHostName() == null) {
status.setOk(false);
status.setDescription(EmailResponse.HOST_CONFIG_NOT_FOUND.getResponseMessage());
status.setResponseObject(EmailResponse.HOST_CONFIG_NOT_FOUND);
return status;
}
String serverBaseUrl = configurationProvider.getServerBaseUrl();
String plainContent = renderPlainContent(text, sender);
String htmlContent = renderHtmlContent(text, footer, serverBaseUrl != null ? HOST + serverBaseUrl : "", sender);
try {
HtmlEmail email = getHtmlEmail(emailConfig.getHostName(), emailConfig.getPort(), emailConfig.getUsername(), emailConfig.getPassword(), emailConfig.isTls(), emailConfig.getFrom());
email.setSubject(getPrefixedSubject(subject));
email.setTextMsg(plainContent);
email.setHtmlMsg(htmlContent);
boolean hasRecipients = false;
for (User user : users) {
boolean doSend = forceSend || (Boolean) userSettingService.getUserSetting(UserSettingKey.MESSAGE_EMAIL_NOTIFICATION, user);
if (doSend && ValidationUtils.emailIsValid(user.getEmail())) {
if (isEmailValid(user.getEmail())) {
email.addBcc(user.getEmail());
hasRecipients = true;
log.info("Sending email to user: " + user.getUsername() + " with email address: " + user.getEmail());
} else {
log.warn(user.getEmail() + " is not a valid email for user: " + user.getUsername());
errorMessage = "No valid email address found";
}
}
}
if (hasRecipients) {
email.send();
log.info("Email sent using host: " + emailConfig.getHostName() + ":" + emailConfig.getPort() + " with TLS: " + emailConfig.isTls());
status = new OutboundMessageResponse("Email sent", EmailResponse.SENT, true);
} else {
status = new OutboundMessageResponse(errorMessage, EmailResponse.ABORTED, false);
}
} catch (Exception ex) {
log.error("Error while sending email: " + ex.getMessage() + ", " + DebugUtils.getStackTrace(ex));
status = new OutboundMessageResponse("Email not sent: " + ex.getMessage(), EmailResponse.FAILED, false);
}
return status;
}
use of org.apache.commons.mail.HtmlEmail in project Japid by branaway.
the class JapidMailer method send.
@SuppressWarnings("unchecked")
public static Future<Boolean> send(Object... args) {
try {
final HashMap<String, Object> infoMap = getInfoMap();
// Body character set
final String charset = (String) infoMap.get(CHARSET);
// Headers
final Map<String, String> headers = (Map<String, String>) infoMap.get(HEADERS);
// Subject
final String subject = (String) infoMap.get(SUBJECT);
// xxx how to determine the method name???
// String templateName = (String) infoMap.get(METHOD);
String templateNameBase = StackTraceUtils.getCaller();
if (!templateNameBase.startsWith("notifiers")) {
throw new RuntimeException("The emailers must be put in the \"notifiers\" package.");
}
// if (templateNameBase.startsWith(NOTIFIERS)) {
// templateNameBase = templateNameBase.substring(NOTIFIERS.length());
// }
// if (templateNameBase.startsWith(CONTROLLERS)) {
// templateNameBase = templateNameBase.substring(CONTROLLERS.length());
// }
// templateNameBase = templateNameBase.substring(0, templateNameBase.indexOf("("));
// templateNameBase = templateNameBase.replace(".", "/");
// final Map<String, Object> templateHtmlBinding = new HashMap<String, Object>();
// final Map<String, Object> templateTextBinding = new HashMap<String, Object>();
// for (Object o : args) {
// List<String> names = LocalVariablesNamesTracer.getAllLocalVariableNames(o);
// for (String name : names) {
// templateHtmlBinding.put(name, o);
// templateTextBinding.put(name, o);
// }
// }
String templateClassName = DirUtil.JAPIDVIEWS_ROOT + "._" + templateNameBase;
String bodyHtml = null;
Class tClass = Play.classloader.getClassIgnoreCase(templateClassName);
if (tClass == null) {
String templateFileName = templateClassName.replace('.', '/') + ".html";
throw new RuntimeException("Japid Emailer: could not find a Japid template with the name of: " + templateFileName);
} else if (JapidTemplateBase.class.isAssignableFrom(tClass)) {
try {
JapidController.render(tClass, args);
} catch (JapidResult jr) {
RenderResult rr = jr.getRenderResult();
bodyHtml = rr.getContent().toString();
}
} else {
throw new RuntimeException("The found class is not a Japid template class: " + templateClassName);
}
// System.out.println("email body: " + bodyHtml);
// The rule is as follow: If we ask for text/plain, we don't care about the HTML
// If we ask for HTML and there is a text/plain we add it as an alternative.
// If contentType is not specified look at the template available:
// - .txt only -> text/plain
// else
// - -> text/html
// String contentType = (String) infoMap.get(CONTENT_TYPE);
// String bodyText = "";
// try {
// Template templateHtml = TemplateLoader.load(templateNameBase + ".html");
// bodyHtml = templateHtml.render(templateHtmlBinding);
// } catch (TemplateNotFoundException e) {
// if (contentType != null && !contentType.startsWith(TEXT_PLAIN)) {
// throw e;
// }
// }
// //
// try {
// Template templateText = TemplateLoader.load(templateName + ".txt");
// bodyText = templateText.render(templateTextBinding);
// } catch (TemplateNotFoundException e) {
// if (bodyHtml == null && (contentType == null || contentType.startsWith(TEXT_PLAIN))) {
// throw e;
// }
// }
// Content type
// bran html for now
// if (contentType == null) {
// if (bodyHtml != null) {
// contentType = TEXT_HTML;
// } else {
// contentType = TEXT_PLAIN;
// }
// }
// Recipients
final List<Object> recipientList = (List<Object>) infoMap.get(RECIPIENTS);
// From
final Object from = infoMap.get(FROM);
final Object replyTo = infoMap.get(REPLY_TO);
Email email = null;
if (infoMap.get(ATTACHMENTS) == null) {
// if (StringUtils.isEmpty(bodyHtml)) {
// email = new SimpleEmail();
// email.setMsg(bodyText);
// } else {
HtmlEmail htmlEmail = new HtmlEmail();
htmlEmail.setHtmlMsg(bodyHtml);
// if (!StringUtils.isEmpty(bodyText)) {
// htmlEmail.setTextMsg(bodyText);
// }
email = htmlEmail;
// }
} else {
// if (StringUtils.isEmpty(bodyHtml)) {
// email = new MultiPartEmail();
// email.setMsg(bodyText);
// } else {
HtmlEmail htmlEmail = new HtmlEmail();
htmlEmail.setHtmlMsg(bodyHtml);
// if (!StringUtils.isEmpty(bodyText)) {
// htmlEmail.setTextMsg(bodyText);
// }
email = htmlEmail;
// }
MultiPartEmail multiPartEmail = (MultiPartEmail) email;
List<EmailAttachment> objectList = (List<EmailAttachment>) infoMap.get(ATTACHMENTS);
for (EmailAttachment object : objectList) {
multiPartEmail.attach(object);
}
}
if (from != null) {
try {
InternetAddress iAddress = new InternetAddress(from.toString());
email.setFrom(iAddress.getAddress(), iAddress.getPersonal());
} catch (Exception e) {
email.setFrom(from.toString());
}
}
if (replyTo != null) {
try {
InternetAddress iAddress = new InternetAddress(replyTo.toString());
email.addReplyTo(iAddress.getAddress(), iAddress.getPersonal());
} catch (Exception e) {
email.addReplyTo(replyTo.toString());
}
}
if (recipientList != null) {
for (Object recipient : recipientList) {
try {
InternetAddress iAddress = new InternetAddress(recipient.toString());
email.addTo(iAddress.getAddress(), iAddress.getPersonal());
} catch (Exception e) {
email.addTo(recipient.toString());
}
}
} else {
throw new MailException("You must specify at least one recipient.");
}
List<Object> ccsList = (List<Object>) infoMap.get(CCS);
if (ccsList != null) {
for (Object cc : ccsList) {
email.addCc(cc.toString());
}
}
List<Object> bccsList = (List<Object>) infoMap.get(BCCS);
if (bccsList != null) {
for (Object bcc : bccsList) {
try {
InternetAddress iAddress = new InternetAddress(bcc.toString());
email.addBcc(iAddress.getAddress(), iAddress.getPersonal());
} catch (Exception e) {
email.addBcc(bcc.toString());
}
}
}
if (!StringUtils.isEmpty(charset)) {
email.setCharset(charset);
}
email.setSubject(subject);
email.updateContentType(TEXT_HTML);
if (headers != null) {
for (String key : headers.keySet()) {
email.addHeader(key, headers.get(key));
}
}
// reset the infomap
infos.remove();
return Mail.send(email);
} catch (EmailException ex) {
throw new MailException("Cannot send email", ex);
}
}
Aggregations