use of org.apache.commons.mail.EmailException in project dal by ctripcorp.
the class GenTaskResource method taskApproveOperation.
@GET
@Path("taskApproveOperation")
@Produces(MediaType.APPLICATION_JSON)
public Status taskApproveOperation(@Context HttpServletRequest request, @QueryParam("taskId") int taskId, @QueryParam("taskType") String taskType, @QueryParam("approveFlag") int approveFlag, @QueryParam("approveMsg") String approveMsg) {
Status status = Status.ERROR;
String userNo = RequestUtil.getUserNo(request);
LoginUser user = SpringBeanGetter.getDaoOfLoginUser().getUserByNo(userNo);
if (user == null) {
status.setInfo("please login fisrt.");
return status;
}
ApproveTask task = haveApprovePermision(user.getId(), taskId, taskType);
if (task == null) {
status.setInfo("you don't have permision to approve this task.");
return status;
}
List<GenTaskByTableViewSp> tableViewSpTasks = new ArrayList<>();
List<GenTaskBySqlBuilder> autoTasks = new ArrayList<>();
List<GenTaskByFreeSql> sqlTasks = new ArrayList<>();
if ("table_view_sp".equalsIgnoreCase(taskType)) {
SpringBeanGetter.getDaoByTableViewSp().updateTask(taskId, approveFlag, approveMsg);
SpringBeanGetter.getApproveTaskDao().deleteApproveTaskByTaskIdAndType(taskId, taskType);
tableViewSpTasks.add(SpringBeanGetter.getDaoByTableViewSp().getTasksByTaskId(taskId));
} else if ("auto".equalsIgnoreCase(taskType)) {
SpringBeanGetter.getDaoBySqlBuilder().updateTask(taskId, approveFlag, approveMsg);
SpringBeanGetter.getApproveTaskDao().deleteApproveTaskByTaskIdAndType(taskId, taskType);
autoTasks.add(SpringBeanGetter.getDaoBySqlBuilder().getTasksByTaskId(taskId));
} else if ("sql".equalsIgnoreCase(taskType)) {
SpringBeanGetter.getDaoByFreeSql().updateTask(taskId, approveFlag, approveMsg);
SpringBeanGetter.getApproveTaskDao().deleteApproveTaskByTaskIdAndType(taskId, taskType);
sqlTasks.add(SpringBeanGetter.getDaoByFreeSql().getTasksByTaskId(taskId));
}
java.util.Collections.sort(tableViewSpTasks);
java.util.Collections.sort(autoTasks);
java.util.Collections.sort(sqlTasks);
LoginUser noticeUsr = SpringBeanGetter.getDaoOfLoginUser().getUserById(task.getCreate_user_id());
VelocityContext context = GenUtils.buildDefaultVelocityContext();
context.put("standardDao", tableViewSpTasks);
context.put("autoDao", autoTasks);
context.put("sqlDao", sqlTasks);
String msg = "你好," + noticeUsr.getUserName() + ":<br/> 你提交的DAO已审批,审批";
if (approveFlag == 2) {
msg += "通过。";
} else {
msg += "未通过。";
}
if (approveMsg != null) {
msg += "<br/> 审批意见:" + approveMsg;
}
context.put("msg", msg);
String mailMsg = GenUtils.mergeVelocityContext(context, "templates/approval/approveResult.tpl");
HtmlEmail email = new HtmlEmail();
email.setHostName(Configuration.get("email_host_name"));
email.setAuthentication(Configuration.get("email_user_name"), Configuration.get("email_password"));
try {
email.addTo(noticeUsr.getUserEmail());
email.setFrom(user.getUserEmail(), user.getUserName());
email.setSubject("Codegen DAO 审批结果通知");
email.setHtmlMsg(mailMsg);
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
return Status.OK;
}
use of org.apache.commons.mail.EmailException in project dal by ctripcorp.
the class GenTaskResource method approveTask.
@POST
@Path("approveTask")
@Produces(MediaType.APPLICATION_JSON)
public Status approveTask(@Context HttpServletRequest request, @FormParam("taskId") String taskId, @FormParam("taskType") String taskType, @FormParam("userId") int userId) {
Status status = Status.ERROR;
LoginUser approver = SpringBeanGetter.getDaoOfLoginUser().getUserById(userId);
if (approver == null) {
return status;
}
int len = request.getRequestURI().length();
String host = request.getRequestURL().toString();
host = host.substring(0, len);
String approveUrl = host + "rest/task/taskApproveOperationForEmail?";
String myApprovelTaskUrl = host + "eventmanage.jsp";
String[] taskIds = taskId.split(",");
String[] taskTypes = taskType.split(",");
List<GenTaskByTableViewSp> tableViewSpTasks = new ArrayList<>();
List<GenTaskBySqlBuilder> autoTasks = new ArrayList<>();
List<GenTaskByFreeSql> sqlTasks = new ArrayList<>();
String userNo = RequestUtil.getUserNo(request);
LoginUser user = SpringBeanGetter.getDaoOfLoginUser().getUserByNo(userNo);
ApproveTask at = new ApproveTask();
at.setApprove_user_id(approver.getId());
at.setCreate_user_id(user.getId());
at.setCreate_time(new Timestamp(System.currentTimeMillis()));
for (int i = 0; i < taskIds.length; i++) {
int id = Integer.parseInt(taskIds[i]);
String type = taskTypes[i].trim();
if ("table_view_sp".equalsIgnoreCase(type)) {
GenTaskByTableViewSp task = SpringBeanGetter.getDaoByTableViewSp().getTasksByTaskId(id);
tableViewSpTasks.add(task);
at.setTask_id(task.getId());
at.setTask_type("table_view_sp");
SpringBeanGetter.getApproveTaskDao().insertApproveTask(at);
} else if ("auto".equalsIgnoreCase(type)) {
GenTaskBySqlBuilder task = SpringBeanGetter.getDaoBySqlBuilder().getTasksByTaskId(id);
autoTasks.add(task);
at.setTask_id(task.getId());
at.setTask_type("auto");
SpringBeanGetter.getApproveTaskDao().insertApproveTask(at);
} else if ("sql".equalsIgnoreCase(type)) {
GenTaskByFreeSql task = SpringBeanGetter.getDaoByFreeSql().getTasksByTaskId(id);
sqlTasks.add(task);
at.setTask_id(task.getId());
at.setTask_type("sql");
SpringBeanGetter.getApproveTaskDao().insertApproveTask(at);
}
}
java.util.Collections.sort(tableViewSpTasks);
java.util.Collections.sort(autoTasks);
java.util.Collections.sort(sqlTasks);
VelocityContext context = GenUtils.buildDefaultVelocityContext();
context.put("standardDao", tableViewSpTasks);
context.put("autoDao", autoTasks);
context.put("sqlDao", sqlTasks);
context.put("approveUrl", approveUrl);
context.put("myApprovelTaskUrl", myApprovelTaskUrl);
context.put("approveUser", approver.getUserName());
String msg = GenUtils.mergeVelocityContext(context, "templates/approval/approveDao.tpl");
HtmlEmail email = new HtmlEmail();
email.setHostName(Configuration.get("email_host_name"));
email.setAuthentication(Configuration.get("email_user_name"), Configuration.get("email_password"));
try {
email.addTo(approver.getUserEmail());
email.setFrom(user.getUserEmail(), user.getUserName());
email.setSubject("Codegen DAO 审批");
email.setHtmlMsg(msg);
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
return Status.OK;
}
use of org.apache.commons.mail.EmailException in project dhis2-core by dhis2.
the class EmailMessageSender method sendMessage.
// -------------------------------------------------------------------------
// MessageSender implementation
// -------------------------------------------------------------------------
/**
* Note this methods is invoked asynchronously.
*/
@Async
@Override
public OutboundMessageResponse sendMessage(String subject, String text, String footer, User sender, Set<User> users, boolean forceSend) {
EmailConfiguration emailConfig = getEmailConfiguration();
String errorMessage = "No recipient found";
OutboundMessageResponse status = new OutboundMessageResponse();
if (emailConfig.getHostName() == null) {
status.setOk(false);
status.setResponseObject(EmailResponse.NOT_CONFIGURED);
return status;
}
String plainContent = renderPlainContent(text, sender);
String htmlContent = renderHtmlContent(text, footer, sender);
try {
HtmlEmail email = getHtmlEmail(emailConfig.getHostName(), emailConfig.getPort(), emailConfig.getUsername(), emailConfig.getPassword(), emailConfig.isTls(), emailConfig.getFrom());
email.setSubject(customizeTitle(DEFAULT_SUBJECT_PREFIX) + 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());
log.info("Sending email to user: " + user.getUsername() + " with email address: " + user.getEmail() + " to host: " + emailConfig.getHostName() + ":" + emailConfig.getPort());
hasRecipients = true;
} else {
log.error(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 (EmailException ex) {
log.warn("Could not send email: " + ex.getMessage() + ", " + DebugUtils.getStackTrace(ex));
status = new OutboundMessageResponse("Email not sent: " + ex.getMessage(), EmailResponse.FAILED, false);
} catch (RuntimeException ex) {
log.warn("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.EmailException in project Japid by branaway.
the class JapidMailer2 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.");
}
String templateClassName = DirUtil.JAPIDVIEWS_ROOT + "._" + templateNameBase;
String bodyHtml = null;
//Play.classloader.getClassIgnoreCase(templateClassName);
Class<? extends JapidTemplateBaseWithoutPlay> tClass = JapidPlayRenderer.getTemplateClass(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 {
try {
JapidController2.render(tClass, args);
} catch (JapidResult jr) {
RenderResult rr = jr.getRenderResult();
bodyHtml = rr.getContent().toString();
}
}
// 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 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 = "japidviews._" + templateNameBase;
String bodyHtml = null;
Class tClass = JapidRenderer.getClass(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)) {
JapidResult jr = JapidController.render(tClass, args);
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 PlayException("JapidMailer", "You must specify at least one recipient.", null);
}
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