`
jacally
  • 浏览: 759512 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

使用Spring邮件抽象层发送简单邮件(转)

    博客分类:
  • JAVA
阅读更多

http://www.blogjava.net/shmily432685/archive/2005/12/30/26041.html

http://www.blogjava.net/Crying/archive/2007/09/22/142701.html

re: 使用Spring邮件抽象层发送简单邮件

java 代码
  1.   
  2. import java.util.*;    
  3. import javax.mail.*;    
  4. import javax.mail.internet.*;    
  5. import javax.activation.*;    
  6. import java.io.*;    
  7.   
  8. public class SendMail    
  9. {    
  10. static final String MAIL_HOST = "61.177.95.155";    
  11. static final boolean MAIL_NEEDAUTH = true;    
  12. static final String DEFAULT_MAIL_USER = "lioulb@126.com";    
  13. static final String DEFAULT_MAIL_PASSWORD = ".......";    
  14. static final String DEFAULT_FORMAT = "plain"//纯文本    
  15. private MimeMessage mimeMsg; //MIME邮件对象    
  16. private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象    
  17. private Session session; //邮件会话对象    
  18. private Properties props; //系统属性    
  19. private boolean needAuth; //smtp是否需要认证    
  20. private String userName; //smtp认证用户名和密码    
  21. private String password; //smtp认证密码    
  22. private String mailFormat = DEFAULT_FORMAT; //邮件文本格式    
  23.   
  24. public SendMail(String host,boolean needAuth,String user,String password)    
  25. //构造方法    
  26. if(host==null||host.trim().equals(""))    
  27. {    
  28. host = MAIL_HOST;    
  29. }    
  30. setHost(host);    
  31. createMimeMessage();    
  32. setAuth(needAuth);    
  33. if(user==null)    
  34. {    
  35. user = "";    
  36. }    
  37. if(password==null)    
  38. {    
  39. password = "";    
  40. }    
  41. setUser(user,password);    
  42. setFrom(user);    
  43. }    
  44.   
  45. public SendMail()    
  46. {    
  47. setHost(MAIL_HOST);    
  48. createMimeMessage();    
  49. setAuth(MAIL_NEEDAUTH);    
  50. setUser(DEFAULT_MAIL_USER,DEFAULT_MAIL_PASSWORD);    
  51. setFrom(DEFAULT_MAIL_USER);    
  52. }    
  53.   
  54. private void setHost(String hostName)    
  55. //设置smtp的主机地址    
  56. if(props==null)    
  57. {    
  58. props = System.getProperties(); //获得系统属性对象    
  59. }    
  60. props.put("mail.smtp.host",hostName); //设置SMTP主机    
  61. }    
  62.   
  63. private void setAuth(boolean need)    
  64. //smtp认证    
  65. if(props==null)    
  66. {    
  67. props = System.getProperties();    
  68. }    
  69. if(need)    
  70. {    
  71. props.put("mail.smtp.auth","true");    
  72. }    
  73. else    
  74. {    
  75. props.put("mail.smtp.auth","false");    
  76. }    
  77. }    
  78.   
  79. private void setUser(String userName,String password)    
  80. //设置smtp用户名和密码    
  81. this.userName = userName;    
  82. this.password = password;    
  83. }    
  84.   
  85. private boolean createMimeMessage()    
  86. //生成邮件对象    
  87. try    
  88. {    
  89. session = Session.getDefaultInstance(props,null); //获得邮件会话对象    
  90. }    
  91. catch(Exception e)    
  92. {    
  93. e.printStackTrace();    
  94. return false;    
  95. }    
  96. try    
  97. {    
  98. mimeMsg = new MimeMessage(session); //创建MIME邮件对象    
  99. mp = new MimeMultipart();    
  100. return true;    
  101. }    
  102. catch(Exception e)    
  103. {    
  104. e.printStackTrace();    
  105. return false;    
  106. }    
  107. }    
  108.   
  109. private void setMailFormat(String format)    
  110. //设置邮件的正文格式 plain:纯文本格式 html:html格式    
  111. if(format==null)    
  112. {    
  113. format = "plain";    
  114. }    
  115. format = format.trim();    
  116. if(format.equals("plain")||format.equals("html"))    
  117. {    
  118. this.mailFormat = "text/"+format;    
  119. }    
  120. else    
  121. {    
  122. this.mailFormat = "text/plain";    
  123. }    
  124. }    
  125.   
  126. public boolean sendMail(String to,String subject,String body,String format)    
  127. //发送不带附件,不转发的邮件    
  128. boolean theReturn = true;    
  129. setMailFormat(format);    
  130. // String aLine = Time.getdate()+" "+Time.gettime()+" send: "+this.userName    
  131. //+" "+to+" "+Common.convertToGb(subject);    
  132.   
  133. String aLine = " send: "+this.userName    
  134. +" "+to+" "+subject;    
  135. if(setSubject(subject)&&setBody(body)&&setTo(to))    
  136. {    
  137. theReturn = sendOut();    
  138. aLine = aLine+" [Success]";    
  139. }    
  140. else    
  141. {    
  142. theReturn = false;    
  143. aLine = aLine+" [Failed]";    
  144. }    
  145.   
  146. return theReturn;    
  147. }    
  148.   
  149. public boolean sendMail(String to,String subject,String body)    
  150. {    
  151. return sendMail(to,subject,body,DEFAULT_FORMAT);    
  152. }    
  153.   
  154. private boolean setSubject(String mailSubject)    
  155. //设置邮件主题    
  156. try    
  157. {    
  158. //mailSubject = Common.convertToGb(mailSubject);    
  159. mimeMsg.setSubject(mailSubject);    
  160. return true;    
  161. }    
  162. catch(Exception e)    
  163. {    
  164. e.printStackTrace();    
  165. return false;    
  166. }    
  167. }    
  168.   
  169. private boolean setBody(String mailBody)    
  170. //设置邮件正文    
  171. try    
  172. {    
  173. //mailBody = Common.convertToGb(mailBody);    
  174. BodyPart bp = new MimeBodyPart();    
  175. bp.setContent(mailBody,this.mailFormat+";charset=GB2312"); //"<meta http-equiv=Content-Type content=text/html; charset=gb2312>"+mailBody    
  176. mp.addBodyPart(bp);    
  177. return true;    
  178. }    
  179. catch(Exception e)    
  180. {    
  181. e.printStackTrace();    
  182. return false;    
  183. }    
  184. }    
  185.   
  186. private boolean setFrom(String from)    
  187. //设置发信人地址    
  188. try    
  189. {    
  190. mimeMsg.setFrom(new InternetAddress(from));    
  191. return true;    
  192. }    
  193. catch(Exception e)    
  194. {    
  195. e.printStackTrace();    
  196. return false;    
  197. }    
  198. }    
  199.   
  200. private boolean setTo(String to)    
  201. //设置收信人地址    
  202. if(to==null)    
  203. {    
  204. return false;    
  205. }    
  206. try    
  207. {    
  208. mimeMsg.addRecipients(Message.RecipientType.TO,InternetAddress.parse(to));    
  209. return true;    
  210. }    
  211. catch(Exception e)    
  212. {    
  213. e.printStackTrace();    
  214. return false;    
  215. }    
  216. }    
  217.   
  218. private boolean addFileAffix(String filename)    
  219. //添加附件    
  220. try    
  221. {    
  222. BodyPart bp = new MimeBodyPart();    
  223. FileDataSource fileds = new FileDataSource(filename);    
  224. bp.setDataHandler(new DataHandler(fileds));    
  225. bp.setFileName(fileds.getName());    
  226. mp.addBodyPart(bp);    
  227. return true;    
  228. }    
  229. catch(Exception e)    
  230. {    
  231. e.printStackTrace();    
  232. return false;    
  233. }    
  234. }    
  235.   
  236. private boolean setCopyTo(String copyto)    
  237. //设置转发人地址    
  238. if(copyto==null)    
  239. {    
  240. return false;    
  241. }    
  242. try    
  243. {    
  244. mimeMsg.addRecipients(Message.RecipientType.CC,    
  245. (Address[])InternetAddress.parse(copyto));    
  246. return true;    
  247. }    
  248. catch(Exception e)    
  249. {    
  250. e.printStackTrace();    
  251. return false;    
  252. }    
  253. }    
  254.   
  255. public int tryToConnect()    
  256. //连接邮箱 1:连接成功 0:连接失败 -1:已经连接或系统忙    
  257. int theReturn = 0;    
  258. // String aLine = Time.getdate()+" "+Time.gettime()+" Connect: "+this.userName    
  259. //+" "+this.userName+" "+this.password;    
  260.   
  261. String aLine = " Connect: "+this.userName    
  262. +" "+this.userName+" "+this.password;    
  263. try    
  264. {    
  265. Session mailSession = Session.getInstance(props,null);    
  266. Transport transport = mailSession.getTransport("smtp");    
  267. transport.connect((String)props.get("mail.smtp.host"),this.userName,    
  268. this.password);    
  269. transport.close();    
  270. theReturn = 1;    
  271. aLine = aLine+" [Success]";    
  272. }    
  273. catch(MessagingException e)    
  274. {    
  275. e.printStackTrace();    
  276. theReturn = 0;    
  277. }    
  278. catch(IllegalStateException e)    
  279. {    
  280. e.printStackTrace();    
  281. theReturn = -1;    
  282. }    
  283. catch(Exception e)    
  284. {    
  285. e.printStackTrace();    
  286. theReturn = 0;    
  287. aLine = aLine+" [Failed]";    
  288. }    
  289. return theReturn;    
  290. }    
  291.   
  292. private boolean sendOut()    
  293. //发送邮件    
  294. try    
  295. {    
  296. mimeMsg.setContent(mp);    
  297. mimeMsg.saveChanges();    
  298. Session mailSession = Session.getInstance(props,null);    
  299. Transport transport = mailSession.getTransport("smtp");    
  300. transport.connect((String)props.get("mail.smtp.host"),this.userName,    
  301. this.password);    
  302. transport.sendMessage(mimeMsg,mimeMsg.getAllRecipients());    
  303. transport.close();    
  304. return true;    
  305. }    
  306. catch(Exception e)    
  307. {    
  308. e.printStackTrace();    
  309. return false;    
  310. }    
  311. }    
  312.   
  313. public boolean changePwd(String userName,String newPwd)    
  314. //修改邮箱密码    
  315. boolean theReturn = false;    
  316. try    
  317. {    
  318. String commond = "passwd "+userName;    
  319. Process process = Runtime.getRuntime().exec(commond);    
  320. BufferedReader br = new BufferedReader(new InputStreamReader(process.    
  321. getInputStream()));    
  322. PrintStream ps = new PrintStream(process.getOutputStream());    
  323. BufferedReader br1 = new BufferedReader(new InputStreamReader(process.    
  324. getErrorStream()));    
  325. char ac[] = new char[1024];    
  326. br1.read(ac);    
  327. ps.println(newPwd);    
  328. ps.flush();    
  329. br1.read(ac);    
  330. ps.println(newPwd);    
  331. ps.flush();    
  332. br1.read(ac);    
  333. if(process.waitFor()==0)    
  334. {    
  335. theReturn = true;    
  336. }    
  337. }    
  338. catch(Exception e)    
  339. {    
  340. e.printStackTrace();    
  341. //e.printStackTrace(System.out);    
  342. System.out.println(e.toString());    
  343. theReturn = false;    
  344. }    
  345. return theReturn;    
  346. }    
  347.   
  348. public boolean addUser(String userName)    
  349. //添加邮件用户 (密码默认为空)    
  350. boolean theReturn = false;    
  351. try    
  352. {    
  353. String commond = "/usr/sbin/useradd "+userName+    
  354. " -g mail -d /dev/null -s /bin/false";    
  355. Process process = Runtime.getRuntime().exec(commond);    
  356. BufferedReader br = new BufferedReader(new InputStreamReader(process.    
  357. getInputStream()));    
  358. PrintStream ps = new PrintStream(process.getOutputStream());    
  359. BufferedReader br1 = new BufferedReader(new InputStreamReader(process.    
  360. getErrorStream()));    
  361. char ac[] = new char[1024];    
  362. br1.read(ac);    
  363. if(process.waitFor()==0)    
  364. {    
  365. theReturn = true;    
  366. }    
  367. }    
  368. catch(Exception e)    
  369. {    
  370. e.printStackTrace(System.out);    
  371. theReturn = false;    
  372. }    
  373. return theReturn;    
  374. }    
  375.   
  376. public boolean addUser(String userName,String pwd)    
  377. //添加邮件用户    
  378. boolean theReturn = addUser(userName);    
  379. if(theReturn)    
  380. {    
  381. theReturn = changePwd(userName,pwd);    
  382. if(!theReturn)    
  383. //修改密码失败    
  384. deleUser(userName);    
  385. }    
  386. }    
  387. return theReturn;    
  388. }    
  389.   
  390. public boolean deleUser(String userName)    
  391. //删除邮件用户    
  392. boolean theReturn = false;    
  393. try    
  394. {    
  395. String commond = "/usr/sbin/userdel "+userName;    
  396. Process process = Runtime.getRuntime().exec(commond);    
  397. BufferedReader br = new BufferedReader(new InputStreamReader(process.    
  398. getInputStream()));    
  399. PrintStream ps = new PrintStream(process.getOutputStream());    
  400. BufferedReader br1 = new BufferedReader(new InputStreamReader(process.    
  401. getErrorStream()));    
  402. char ac[] = new char[1024];    
  403. br1.read(ac);    
  404. if(process.waitFor()==0)    
  405. {    
  406. theReturn = true;    
  407. }    
  408. }    
  409. catch(Exception exception)    
  410. {    
  411. exception.printStackTrace(System.out);    
  412. theReturn = false;    
  413. }    
  414. return theReturn;    
  415. }    
  416.   
  417. public static void main(String args[]){    
  418. SendMail myMail=new SendMail();    
  419. System.out.println(myMail.sendMail("oxservice@126.com","this is test","my \n test"));    
  420. }    
  421. }    
分享到:
评论

相关推荐

    spring邮件抽象层详解

    spring邮件抽象层详解,简单的方式发送email

    spring各种邮件发送

    Spring邮件抽象层的主要包为org.springframework.mail。它包括了发送电子邮件的主要接口MailSender,和值对象SimpleMailMessage,它封装了简单邮件的属性如from, to,cc, subject,text。 包里还包含一棵以...

    SpringMailTest.zip

    Spring邮件抽象层的主要包为org.springframework.mail。它包括了发送电子邮件的主要接口MailSender(实现类为org.springframework.mail.javamail.JavaMailSenderImpl,下面会用到改实现类)和封装了简单邮件属性的值...

    Spring 2.0 开发参考手册

    6.8.4. 在Spring应用中使用AspectJ Load-time weaving(LTW) 6.9. 其它资源 7. Spring AOP APIs 7.1. 简介 7.2. Spring中的切入点API 7.2.1. 概念 7.2.2. 切入点实施 7.2.3. AspectJ切入点表达式 7.2.4. ...

    Spring-Reference_zh_CN(Spring中文参考手册)

    6.8.1. 在Spring中使用AspectJ来为domain object进行依赖注入 6.8.1.1. @Configurable object的单元测试 6.8.1.2. 多application context情况下的处理 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来...

    spring chm文档

    Spring Framework 开发参考手册 Rod Johnson Juergen Hoeller Alef Arendsen Colin Sampaleanu Rob Harrop Thomas Risberg Darren Davison Dmitriy Kopylenko Mark Pollack ...19.2. 使用Spring JMS ...

    Spring中文帮助文档

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    Spring API

    6.8.1. 在Spring中使用AspectJ进行domain object的依赖注入 6.8.2. Spring中其他的AspectJ切面 6.8.3. 使用Spring IoC来配置AspectJ的切面 6.8.4. 在Spring应用中使用AspectJ加载时织入(LTW) 6.9. 更多资源 7...

    开源框架 Spring Gossip

    简单邮件 HTML 邮件 内嵌图片或附档 排程 Spring则对 java.util.Timer提供了抽象封装,让您可以善用Spring的容器管理功能,而Spring对Quartz进行了封装,让它在使用上更加方便。 使用 ...

    Spring.3.x企业应用开发实战(完整版).part2

    Spring3.0是Spring在积蓄了3年之久后,隆重推出的一个重大升级版本,进一步加强了Spring作为Java领域第一开源平台的翘楚地位。  Spring3.0引入了众多Java...附录A JavaMail发送邮件 附录B 在Spring中开发Web Service

    spring-email-master:使用spring4.3.4 发送邮件,三种方式:文本格式,HTML格式,velocity模版,Thymeleaf模版,使用模版以及策略设计模式实现同步和异步发送

    Spring Email抽象核心接口MailSender,其实现类JavaMailSenderImpl,在其中配置邮件 服务器host,pssword,协议等 。。。。。 1.发送简单的消息 SimpleMailMessage:发送简单的消息 2.发送丰富的消息(比如带有附件,内...

    Spring in Action(第2版)中文版

    5.3.3使用spring对jdbc的dao支持类 5.4在spring里集成hibernate 5.4.1选择hibernate的版本 5.4.2使用hibernate模板 5.4.3建立基于hibernate的dao 5.4.4使用hibernate3上下文会话 5.5spring和java持久api ...

    spring framework 开发参考手册

    你可以使用 IoC容器,在其上使用Struts,但是你也可以选择使用 Hibernate 整合代码或者 JDBC 抽象层。 我们将Spring设计为非侵入式的(并且以后也是如此),这意味着应用基本上不需要依赖框架本身 (或者肯定是最小...

    Spring3.x企业应用开发实战(完整版) part1

    Spring3.0是Spring在积蓄了3年之久后,隆重推出的一个重大升级版本,进一步加强了Spring作为Java领域第一开源平台的翘楚地位。  Spring3.0引入了众多Java...附录A JavaMail发送邮件 附录B 在Spring中开发Web Service

    Spring in Action(第二版 中文高清版).part2

    5.3.3 使用Spring对JDBC的DAO支持类 5.4 在Spring里集成Hibernate 5.4.1 选择Hibernate的版本 5.4.2 使用Hibernate模板 5.4.3 建立基于Hibernate的DAO 5.4.4 使用Hibernate 3上下文会话 5.5 Spring和Java...

    Spring in Action(第二版 中文高清版).part1

    5.3.3 使用Spring对JDBC的DAO支持类 5.4 在Spring里集成Hibernate 5.4.1 选择Hibernate的版本 5.4.2 使用Hibernate模板 5.4.3 建立基于Hibernate的DAO 5.4.4 使用Hibernate 3上下文会话 5.5 Spring和Java...

    Spring Framework 开发参考手册

    你可以使用 IoC容器,在其上使用Struts,但是你也可以选择使用 Hibernate 整合代码或者 JDBC 抽象层。 我们将Spring设计为非侵入式的(并且以后也是如此),这意味着应用基本上不需要依赖框架本身 (或者肯定是最小...

    Spring面试题

    ☆ Spring DAO:JDBC DAO 抽象层提供了有意义的异常层次结构,可用该结构来管理异常处理和不同数据库供应商抛出的错误消息。异常层次结构简化了错误处理,并且极大地降低了需要编写的异常代码数量(例如打开和关闭...

    128元尚硅谷Java视频教程_Spring Boot视频教程(下)整合篇

    着重介绍SpringBoot的与各大场景的整合使用,内容包括:缓存(整合Redis),消息中间件(整合RabbitMQ),检索(整合ElasticSearch),任务(异步任务,定时任务,邮件任务),安全(整合SpringSecurity),分布式...

    尚硅谷Java视频教程_Spring Boot视频教程(下)整合篇

    00、尚硅谷_SpringBoot_源码、课件 1、尚硅谷-SpringBoot高级-缓存-JSR107简介 2、尚硅谷-SpringBoot高级-缓存-Spring缓存抽象简介 3、尚硅谷-SpringBoot高级-缓存-基本环境搭建 4、尚硅谷-SpringBoot高级-缓存-@...

Global site tag (gtag.js) - Google Analytics