JBPM3 邮件发送终极解决办法

来源:互联网 发布:nike足球淘宝 编辑:程序博客网 时间:2024/06/14 09:53
Xml代码 复制代码 收藏代码
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <process-definitionxmlns=""name="mail">
  3. <start-statename="start-state1">
  4. <transitionto="mail-node1"></transition>
  5. </start-state>
  6. <mail-nodename="mail-node1"template="test">
  7. <eventtype="node-enter">
  8. <script>
  9. print(&quot;enter mail node&quot;)
  10. </script>
  11. </event>
  12. <eventtype="node-leave">
  13. <script>
  14. print(&quot;leave mail node&quot;)
  15. </script>
  16. </event>
  17. <transitionto="end-state1"></transition>
  18. </mail-node>
  19. <end-statename="end-state1"></end-state>
  20. </process-definition>

这是processdefinition.xml
然后是:
Xml代码 复制代码 收藏代码
  1. <jbpm-configuration>
  2. <stringname="jbpm.mail.smtp.host"value="smtp.163.com"/>
  3. <beanname="jbpm.mail.address.resolver"class="com.whqhoo.mail.TestMail"
  4. singleton="true"/>
  5. <stringname="mail.class.name"value="com.whqhoo.utils.Mail"/>
  6. <stringname="jbpm.mail.from.address"value="whqmse@163.com"/>
  7. <stringname='resource.mail.properties'value='jbpm.mail.properties'/>
  8. </jbpm-configuration>
jbpm.cfg.xml
要新建一个properties
Java代码 复制代码 收藏代码
  1. mail.smtp.host=smtp.163.com
  2. mail.smtp.port=25
  3. mail.smtp.user=你的用户名
  4. mail.smtp.password=你的密码
  5. mail.smtp.ssl=true
  6. mail.smtp.auth=true

Java代码 复制代码 收藏代码
  1. package com.whqhoo.utils;
  2. import java.io.InputStream;
  3. import java.io.Serializable;
  4. import java.util.ArrayList;
  5. import java.util.Arrays;
  6. import java.util.Collection;
  7. import java.util.Date;
  8. import java.util.HashMap;
  9. import java.util.Iterator;
  10. import java.util.List;
  11. import java.util.Map;
  12. import java.util.Properties;
  13. import java.util.StringTokenizer;
  14. import javax.mail.Message;
  15. import javax.mail.PasswordAuthentication;
  16. import javax.mail.Session;
  17. import javax.mail.Transport;
  18. import javax.mail.internet.InternetAddress;
  19. import javax.mail.internet.MimeMessage;
  20. import javax.mail.Authenticator;
  21. import org.apache.commons.logging.Log;
  22. import org.apache.commons.logging.LogFactory;
  23. import org.jbpm.JbpmConfiguration;
  24. import org.jbpm.JbpmException;
  25. import org.jbpm.graph.def.ActionHandler;
  26. import org.jbpm.graph.exe.ExecutionContext;
  27. import org.jbpm.jpdl.el.ELException;
  28. import org.jbpm.jpdl.el.VariableResolver;
  29. import org.jbpm.jpdl.el.impl.JbpmExpressionEvaluator;
  30. import org.jbpm.mail.AddressResolver;
  31. import org.jbpm.util.ClassLoaderUtil;
  32. import org.jbpm.util.XmlUtil;
  33. public class Mailimplements ActionHandler {
  34. private staticfinal long serialVersionUID = 1L;
  35. String template = null;
  36. String actors = null;
  37. String to = null;
  38. String bcc = null;
  39. String bccActors = null;
  40. String subject = null;
  41. String text = null;
  42. ExecutionContext executionContext = null;
  43. public Mail() {
  44. }
  45. public Mail(String template,
  46. String actors,
  47. String to,
  48. String subject,
  49. String text) {
  50. this.template = template;
  51. this.actors = actors;
  52. this.to = to;
  53. this.subject = subject;
  54. this.text = text;
  55. }
  56. public Mail(String template,
  57. String actors,
  58. String to,
  59. String bccActors,
  60. String bcc,
  61. String subject,
  62. String text) {
  63. this.template = template;
  64. this.actors = actors;
  65. this.to = to;
  66. this.bccActors = bccActors;
  67. this.bcc = bcc;
  68. this.subject = subject;
  69. this.text = text;
  70. }
  71. public void execute(ExecutionContext executionContext) {
  72. this.executionContext = executionContext;
  73. send();
  74. }
  75. public List getRecipients() {
  76. List recipients = new ArrayList();
  77. if (actors!=null) {
  78. String evaluatedActors = evaluate(actors);
  79. List tokenizedActors = tokenize(evaluatedActors);
  80. if (tokenizedActors!=null) {
  81. recipients.addAll(resolveAddresses(tokenizedActors));
  82. }
  83. }
  84. if (to!=null) {
  85. String resolvedTo = evaluate(to);
  86. recipients.addAll(tokenize(resolvedTo));
  87. }
  88. return recipients;
  89. }
  90. public List getBccRecipients() {
  91. List recipients = new ArrayList();
  92. if (bccActors!=null) {
  93. String evaluatedActors = evaluate(bccActors);
  94. List tokenizedActors = tokenize(evaluatedActors);
  95. if (tokenizedActors!=null) {
  96. recipients.addAll(resolveAddresses(tokenizedActors));
  97. }
  98. }
  99. if (bcc!=null) {
  100. String resolvedTo = evaluate(to);
  101. recipients.addAll(tokenize(resolvedTo));
  102. }
  103. if (JbpmConfiguration.Configs.hasObject("jbpm.mail.bcc.address")) {
  104. recipients.addAll(tokenize(
  105. JbpmConfiguration.Configs.getString("jbpm.mail.bcc.address")));
  106. }
  107. return recipients;
  108. }
  109. public String getSubject() {
  110. if (subject==null)return null;
  111. return evaluate(subject);
  112. }
  113. public String getText() {
  114. if (text==null)return null;
  115. return evaluate(text);
  116. }
  117. public String getFromAddress() {
  118. if (JbpmConfiguration.Configs.hasObject("jbpm.mail.from.address")) {
  119. return JbpmConfiguration.Configs.getString("jbpm.mail.from.address");
  120. }
  121. return "jbpm@noreply";
  122. }
  123. public void send() {
  124. if (template!=null) {
  125. Properties properties = getMailTemplateProperties(template);
  126. if (actors==null) {
  127. actors = properties.getProperty("actors");
  128. }
  129. if (to==null) {
  130. to = properties.getProperty("to");
  131. }
  132. if (subject==null) {
  133. subject = properties.getProperty("subject");
  134. }
  135. if (text==null) {
  136. text = properties.getProperty("text");
  137. }
  138. if (bcc==null) {
  139. bcc = properties.getProperty("bcc");
  140. }
  141. if (bccActors==null) {
  142. bccActors = properties.getProperty("bccActors");
  143. }
  144. }
  145. send(getMailServerProperties(),
  146. getFromAddress(),
  147. getRecipients(),
  148. getBccRecipients(),
  149. getSubject(),
  150. getText());
  151. }
  152. public staticvoid send(Properties mailServerProperties, String fromAddress, List recipients, String subject, String text) {
  153. send(mailServerProperties, fromAddress, recipients, null, subject, text);
  154. }
  155. public staticvoid send(Properties mailServerProperties, String fromAddress, List recipients, List bccRecipients, String subject, String text) {
  156. if ( (recipients==null)
  157. || (recipients.isEmpty())
  158. ) {
  159. log.debug("skipping mail because there are no recipients");
  160. return;
  161. }
  162. mailServerProperties.put("mail.smtp.auth","true");
  163. log.debug("sending email to '"+recipients+"' about '"+subject+"'");
  164. /**
  165. * 添加认证类
  166. * royzhou 2009.07.21
  167. */
  168. String userName = mailServerProperties.getProperty("mail.smtp.user").toString();
  169. String password = mailServerProperties.getProperty("mail.smtp.password").toString();
  170. MyAuthentication myAuthentication = new MyAuthentication(userName,password);
  171. Session session = Session.getDefaultInstance(mailServerProperties, myAuthentication);
  172. MimeMessage message = new MimeMessage(session);
  173. try {
  174. if (fromAddress!=null) {
  175. message.setFrom(new InternetAddress(fromAddress));
  176. }
  177. Iterator iter = recipients.iterator();
  178. while (iter.hasNext()) {
  179. InternetAddress recipient = new InternetAddress((String) iter.next());
  180. message.addRecipient(Message.RecipientType.TO, recipient);
  181. }
  182. if (bccRecipients!=null) {
  183. iter = bccRecipients.iterator();
  184. while (iter.hasNext()) {
  185. InternetAddress recipient = new InternetAddress((String) iter.next());
  186. message.addRecipient(Message.RecipientType.BCC, recipient);
  187. }
  188. }
  189. if (subject!=null) {
  190. message.setSubject(subject);
  191. }
  192. if (text!=null) {
  193. message.setText(text);
  194. }
  195. message.setSentDate(new Date());
  196. Transport.send(message);
  197. } catch (Exception e) {
  198. throw new JbpmException("couldn't send email", e);
  199. }
  200. }
  201. protected List tokenize(String text) {
  202. if (text==null) {
  203. return null;
  204. }
  205. List list = new ArrayList();
  206. StringTokenizer tokenizer = new StringTokenizer(text,";:");
  207. while (tokenizer.hasMoreTokens()) {
  208. list.add(tokenizer.nextToken());
  209. }
  210. return list;
  211. }
  212. protected Collection resolveAddresses(List actorIds) {
  213. List emailAddresses = new ArrayList();
  214. Iterator iter = actorIds.iterator();
  215. while (iter.hasNext()) {
  216. String actorId = (String) iter.next();
  217. AddressResolver addressResolver = (AddressResolver) JbpmConfiguration.Configs.getObject("jbpm.mail.address.resolver");
  218. Object resolvedAddresses = addressResolver.resolveAddress(actorId);
  219. if (resolvedAddresses!=null) {
  220. if (resolvedAddresses instanceof String) {
  221. emailAddresses.add((String)resolvedAddresses);
  222. } else if (resolvedAddressesinstanceof Collection) {
  223. emailAddresses.addAll((Collection)resolvedAddresses);
  224. } else if (resolvedAddressesinstanceof String[]) {
  225. emailAddresses.addAll(Arrays.asList((String[])resolvedAddresses));
  226. } else {
  227. throw new JbpmException("Address resolver '"+addressResolver+"' returned '"+resolvedAddresses.getClass().getName()+"' instead of a String, Collection or String-array: "+resolvedAddresses);
  228. }
  229. }
  230. }
  231. return emailAddresses;
  232. }
  233. Properties getMailServerProperties() {
  234. Properties mailServerProperties = new Properties();
  235. if (JbpmConfiguration.Configs.hasObject("resource.mail.properties")) {
  236. String mailServerPropertiesResource = JbpmConfiguration.Configs.getString("resource.mail.properties");
  237. try {
  238. InputStream mailServerStream = ClassLoaderUtil.getStream(mailServerPropertiesResource);
  239. mailServerProperties.load(mailServerStream);
  240. } catch (Exception e) {
  241. throw new JbpmException("couldn't get configuration properties for jbpm mail server from resource '"+mailServerPropertiesResource+"'", e);
  242. }
  243. } else if (JbpmConfiguration.Configs.hasObject("jbpm.mail.smtp.host")) {
  244. String smtpServer = JbpmConfiguration.Configs.getString("jbpm.mail.smtp.host");
  245. mailServerProperties.put("mail.smtp.host", smtpServer);
  246. } else {
  247. log.error("couldn't get mail properties");
  248. }
  249. return mailServerProperties;
  250. }
  251. static Map templates = null;
  252. static Map templateVariables =null;
  253. synchronized Properties getMailTemplateProperties(String templateName) {
  254. if (templates==null) {
  255. templates = new HashMap();
  256. String mailTemplatesResource = JbpmConfiguration.Configs.getString("resource.mail.templates");
  257. org.w3c.dom.Element mailTemplatesElement = XmlUtil.parseXmlResource(mailTemplatesResource).getDocumentElement();
  258. List mailTemplateElements = XmlUtil.elements(mailTemplatesElement, "mail-template");
  259. Iterator iter = mailTemplateElements.iterator();
  260. while (iter.hasNext()) {
  261. org.w3c.dom.Element mailTemplateElement = (org.w3c.dom.Element) iter.next();
  262. Properties templateProperties = new Properties();
  263. addTemplateProperty(mailTemplateElement, "actors", templateProperties);
  264. addTemplateProperty(mailTemplateElement, "to", templateProperties);
  265. addTemplateProperty(mailTemplateElement, "subject", templateProperties);
  266. addTemplateProperty(mailTemplateElement, "text", templateProperties);
  267. addTemplateProperty(mailTemplateElement, "bcc", templateProperties);
  268. addTemplateProperty(mailTemplateElement, "bccActors", templateProperties);
  269. templates.put(mailTemplateElement.getAttribute("name"), templateProperties);
  270. }
  271. templateVariables = new HashMap();
  272. List variableElements = XmlUtil.elements(mailTemplatesElement, "variable");
  273. iter = variableElements.iterator();
  274. while (iter.hasNext()) {
  275. org.w3c.dom.Element variableElement = (org.w3c.dom.Element) iter.next();
  276. templateVariables.put(variableElement.getAttribute("name"), variableElement.getAttribute("value"));
  277. }
  278. }
  279. return (Properties) templates.get(templateName);
  280. }
  281. void addTemplateProperty(org.w3c.dom.Element mailTemplateElement, String property, Properties templateProperties) {
  282. org.w3c.dom.Element element = XmlUtil.element(mailTemplateElement, property);
  283. if (element!=null) {
  284. templateProperties.put(property, XmlUtil.getContentText(element));
  285. }
  286. }
  287. String evaluate(String expression) {
  288. if (expression==null) {
  289. return null;
  290. }
  291. VariableResolver variableResolver = JbpmExpressionEvaluator.getUsedVariableResolver();
  292. if (variableResolver!=null) {
  293. variableResolver = new MailVariableResolver(templateVariables, variableResolver);
  294. }
  295. return (String) JbpmExpressionEvaluator.evaluate(expression, executionContext, variableResolver,null);
  296. }
  297. class MailVariableResolver implements VariableResolver, Serializable {
  298. private staticfinal long serialVersionUID = 1L;
  299. Map templateVariables = null;
  300. VariableResolver variableResolver = null;
  301. public MailVariableResolver(Map templateVariables, VariableResolver variableResolver) {
  302. this.templateVariables = templateVariables;
  303. this.variableResolver = variableResolver;
  304. }
  305. public Object resolveVariable(String pName)throws ELException {
  306. if ( (templateVariables!=null)
  307. && (templateVariables.containsKey(pName))
  308. ){
  309. return templateVariables.get(pName);
  310. }
  311. return variableResolver.resolveVariable(pName);
  312. }
  313. }
  314. private static Log log = LogFactory.getLog(Mail.class);
  315. }
  316. /**
  317. * 邮箱认证类
  318. * @author royzhou
  319. * 2009.07.21
  320. */
  321. class MyAuthentication extends Authenticator {
  322. private String userName;
  323. private String password;
  324. public MyAuthentication(String userName, String password) {
  325. this.userName = userName;
  326. this.password = password;
  327. }
  328. protected PasswordAuthentication getPasswordAuthentication() {
  329. return new PasswordAuthentication(userName,password);
  330. }
  331. }

因为在jbpm核心包org.jbpm.mail包中 Mail类 没有对smtp登陆时候有用户名和密码认证的方法。所以,重新写一个类,把相关方法添加进来。并在jbpm.cfg.xml中
Xml代码 复制代码 收藏代码
  1. <jbpm-configuration>
  2. <stringname="mail.class.name"value="com.whqhoo.utils.Mail"/>
  3. <stringname='resource.mail.properties'value='jbpm.mail.properties'/>
  4. </jbpm-configuration>
把properties和重新写的Mail类,注入进去。

然后编写获取收取邮件的类
Java代码 复制代码 收藏代码
  1. package com.whqhoo.mail;
  2. import org.jbpm.mail.AddressResolver;
  3. public class TestMailimplements AddressResolver {
  4. public Object resolveAddress(String actorId) {
  5. return "whqhoo@yahoo.com.cn";
  6. }
  7. }

也要在jbpm.cfg.xml中进行注入
Java代码 复制代码 收藏代码
  1. <bean name="jbpm.mail.address.resolver"class="com.whqhoo.mail.TestMail"
  2. singleton="true" />

以上完成后测试类
Java代码 复制代码 收藏代码
  1. public class TestMailNode {
  2. public staticvoid main(String[] args) {
  3. ProcessDefinition processDefinition = ProcessDefinition.parseXmlResource("mail/processDefinition.xml");
  4. ProcessInstance processInstance = new ProcessInstance(processDefinition);
  5. processInstance.getContextInstance().setVariable("actorId","whqhoo");
  6. Token token = processInstance.getRootToken();
  7. token.signal();
  8. System.out.println("end^^^^^^^^^^^^");
  9. }
  10. }


以上实现,可以正常收发邮件,有问题可以留言。请务必检查配置文件是否正确
503错误,及其他错误,均和配置文件有关系。
注:以上jbpm.cfg.xml都是一个文件,下面只是说明该文件中每行代表的意义
感谢royzhou先生的博文
http://royzhou.iteye.com
原创粉丝点击