use of org.apache.commons.mail.EmailException 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);
}
}
use of org.apache.commons.mail.EmailException in project japid42 by branaway.
the class Mail method send.
/**
* Send an email
*/
public static Future<Boolean> send(Email email) {
try {
email = buildMessage(email);
// has to use this since mail.smtp is a tree in play2
String string = getConfig("mail.smtp.host");
if (string != null)
if (string.equals("mock") && Play.isDev()) {
Mock.send(email);
return new Future<Boolean>() {
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
public boolean isCancelled() {
return false;
}
public boolean isDone() {
return true;
}
public Boolean get() throws InterruptedException, ExecutionException {
return true;
}
public Boolean get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return true;
}
};
}
email.setMailSession(getSession());
return sendMessage(email);
} catch (EmailException ex) {
throw new MailException("Cannot send email", ex);
}
}
use of org.apache.commons.mail.EmailException in project AuthMeReloaded by AuthMe.
the class EmailService method sendRecoveryCode.
/**
* Sends an email to the user with a recovery code for the password recovery process.
*
* @param name the name of the player
* @param email the player's email address
* @param code the recovery code
* @return true if email could be sent, false otherwise
*/
public boolean sendRecoveryCode(String name, String email, String code) {
HtmlEmail htmlEmail;
try {
htmlEmail = sendMailSsl.initializeMail(email);
} catch (EmailException e) {
ConsoleLogger.logException("Failed to create email for recovery code:", e);
return false;
}
String message = replaceTagsForRecoveryCodeMail(settings.getRecoveryCodeEmailMessage(), name, code, settings.getProperty(SecuritySettings.RECOVERY_CODE_HOURS_VALID));
return sendMailSsl.sendEmail(message, htmlEmail);
}
use of org.apache.commons.mail.EmailException in project AuthMeReloaded by AuthMe.
the class EmailService method sendPasswordMail.
/**
* Sends an email to the user with his new password.
*
* @param name the name of the player
* @param mailAddress the player's email
* @param newPass the new password
* @return true if email could be sent, false otherwise
*/
public boolean sendPasswordMail(String name, String mailAddress, String newPass) {
if (!hasAllInformation()) {
ConsoleLogger.warning("Cannot perform email registration: not all email settings are complete");
return false;
}
HtmlEmail email;
try {
email = sendMailSsl.initializeMail(mailAddress);
} catch (EmailException e) {
ConsoleLogger.logException("Failed to create email with the given settings:", e);
return false;
}
String mailText = replaceTagsForPasswordMail(settings.getPasswordEmailMessage(), name, newPass);
// Generate an image?
File file = null;
if (settings.getProperty(EmailSettings.PASSWORD_AS_IMAGE)) {
try {
file = generateImage(name, newPass);
mailText = embedImageIntoEmailContent(file, email, mailText);
} catch (IOException | EmailException e) {
ConsoleLogger.logException("Unable to send new password as image for email " + mailAddress + ":", e);
}
}
boolean couldSendEmail = sendMailSsl.sendEmail(mailText, email);
FileUtils.delete(file);
return couldSendEmail;
}
use of org.apache.commons.mail.EmailException in project AuthMeReloaded by AuthMe.
the class SendMailSsl method sendEmail.
/**
* Sets the given content to the HtmlEmail object and sends it.
*
* @param content the content to set
* @param email the email object to send
* @return true upon success, false otherwise
*/
public boolean sendEmail(String content, HtmlEmail email) {
Thread.currentThread().setContextClassLoader(SendMailSsl.class.getClassLoader());
// Issue #999: Prevent UnsupportedDataTypeException: no object DCH for MIME type multipart/alternative
// cf. http://stackoverflow.com/questions/21856211/unsupporteddatatypeexception-no-object-dch-for-mime-type
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content- handler=com.sun.mail.handlers.message_rfc822");
try {
email.setHtmlMsg(content);
email.setTextMsg(content);
} catch (EmailException e) {
ConsoleLogger.logException("Your email.html config contains an error and cannot be sent:", e);
return false;
}
try {
email.send();
return true;
} catch (EmailException e) {
ConsoleLogger.logException("Failed to send a mail to " + email.getToAddresses() + ":", e);
return false;
}
}
Aggregations