基于Javamail的邮件收取类(可直接使用)
- 格式:doc
- 大小:51.50 KB
- 文档页数:7
1.邮件1.1 邮件组成部分如果是新邮件就获取,并解析它;邮件是由邮件头和邮件体组成,在邮件头中主要包含了收件人、发件人、主题等等基础信息。
而邮件体中就包括了邮件的正文和附件等内容信息。
下图就是pop3协议下,邮件的大致内容。
1.2 发送邮件(带附件、正文带图片)QQ邮箱为例:需要QQ账号和QQ登录第三方客户端时,密码框的“授权码”(相当于密码)授权码如下获取:代码如下:public class JavaMailboxAttachment {private MimeMessage message;private Session session;private String mailHost = "";private String mailAuth = "";private String mailPort = "";private String sender_username = "";private String sender_password = "";//定义一个Properties 用于存放信息private Properties properties = new Properties();//-------------------------------发信箱---------------------------------------------public JavaMailboxAttachment(String email_type) {try {properties.put("mail.smtp.host",""); //发送邮件服务器//端口号,QQ邮箱给出了两个端口,但是另一个我一直使用不了,所以就给出这一个587properties.put("mail.smtp.port", "587"); //发送邮件端口号properties.put("mail.smtp.auth", "true");// 此处填写你的账号properties.put("er", "xxxxxxxxx@");// 此处的密码就是前面说的16位STMP授权码properties.put("mail.password", "xxxxxxxxxxxxxxxx");this.mailHost = properties.getProperty("mail.smtp.host");this.mailAuth = properties.getProperty("mail.smtp.auth");this.mailPort = properties.getProperty("mail.smtp.port");this.sender_username = properties.getProperty("er");this.sender_password = properties.getProperty("mail.password");} catch (Exception e) {e.printStackTrace();}// 构建授权信息,用于进行SMTP进行身份验证Authenticator authenticator = new Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {// 用户名、密码String userName = properties.getProperty("er");String password = properties.getProperty("mail.password");return new PasswordAuthentication(userName, password);}};session = Session.getInstance(properties,authenticator); //用户验证message = new MimeMessage(session); //将验证成功的session信息,创建一个message 对象。
基于Javamail的邮件收发系统使用说明书基于Javamail的邮件收发系统是一款简单、方便、快捷的邮件系统。
它能实现邮件的接收与发送,并能完成附件的传输,具有较好的人机交互性,易于使用。
开发环境:JDK1.6 + Windows平台开发技术:Javamail开发工具:Eclipse3.4运行环境:PC上需安装JDK1.6,且正确配置环境变量。
系统基本功能如下:(1) 收取并显示POP3邮件服务器上指定邮箱的邮件;(2) 使用SMTP邮件服务器发送邮件;(3) 邮件附件的发送与接受;(4) 删除邮件;具体操作步骤如下:1、打开javamailsystem文件夹,找到javamail.jar可执行文件,双击该执行文件,即可打开Javamail邮件收发系统客户端软件。
进入该系统后,首先选择“POP3/SMTP设置”按钮,对收发邮件所需的邮件服务器主机、收发邮件账号及密码信息进行设置。
图1-1邮件客户端主界面设置举例如下:POP3属性POP3服务器:(或或)Email地址:shinning191@(ceshi2009ok@、qiufeng006@)账户名:shinning191(ceshi2009ok、qiufeng006)密码:6857191(123456、28912786)SMTP属性SMTP服务器:(或或)Email地址:shinning191@(ceshi2009ok@\qiufeng006@)账户名:shinning191(ceshi2009ok、qiufeng006)密码:6857191(123456、28912786)在对SMTP/POP3进行设置的时候,由于系统的缺陷,需要先对POP3进行属性设置,然后确定关闭该对话框;重新打开属性设置对话框,对SMTP进行属性设置,确定。
这样便可以正确设置完邮件服务器的属性。
此系统对上述设置的信息具有存储功能,在这里,我们采用属性文件的形式存储SMT P 和POP3邮件服务器属性设置。
javaMail邮件接收解析内容及附件及删除邮件使⽤javaMail获取邮件内容。
⼯具类可直接使⽤。
package com.szy.project.utils;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Properties;import javax.mail.Address;import javax.mail.BodyPart;import javax.mail.Flags;import javax.mail.Folder;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Multipart;import javax.mail.Part;import javax.mail.Session;import javax.mail.Store;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.mail.internet.MimeUtility;/*** 邮件接受测试**//*** 使⽤POP3协议接收邮件*/public class POP3ReceiveMailTest {public static void main(String[] args) throws Exception {resceive();}/*** 接收邮件*/public static void resceive() throws Exception { /** * 因为现在使⽤的是163邮箱⽽163的 pop地址是 端⼝是 110 * ⽐如使⽤好未来企业邮箱就需要换成好未来邮箱的 pop服务器地址 和端⼝110 */ String duankou = "110"; // 端⼝号 String servicePath = ""; // 服务器地址// 准备连接服务器的会话信息Properties props = new Properties();props.setProperty("mail.store.protocol", "pop3"); // 使⽤pop3协议props.setProperty("mail.pop3.port", duankou); // 端⼝props.setProperty("mail.pop3.host", servicePath); // pop3服务器// 创建Session实例对象Session session = Session.getInstance(props);Store store = session.getStore("pop3");store.connect("157********@", "***********"); //163邮箱程序登录属于第三⽅登录所以这⾥的密码是163给的授权密码⽽并⾮普通的登录密码// 获得收件箱Folder folder = store.getFolder("INBOX");/* Folder.READ_ONLY:只读权限* Folder.READ_WRITE:可读可写(可以修改邮件的状态)*/folder.open(Folder.READ_WRITE); //打开收件箱// 由于POP3协议⽆法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数System.out.println("未读邮件数: " + folder.getUnreadMessageCount());// 由于POP3协议⽆法获知邮件的状态,所以下⾯得到的结果始终都是为0System.out.println("删除邮件数: " + folder.getDeletedMessageCount());System.out.println("新邮件: " + folder.getNewMessageCount());// 获得收件箱中的邮件总数System.out.println("邮件总数: " + folder.getMessageCount());// 得到收件箱中的所有邮件,并解析Message[] messages = folder.getMessages();parseMessage(messages);//得到收件箱中的所有邮件并且删除邮件deleteMessage(messages);//释放资源folder.close(true);store.close();}/*** 解析邮件* @param messages 要解析的邮件列表*/public static void parseMessage(Message ...messages) throws MessagingException, IOException {if (messages == null || messages.length < 1)throw new MessagingException("未找到要解析的邮件!");// 解析所有邮件for (int i = 0, count = messages.length; i < count; i++) {MimeMessage msg = (MimeMessage) messages[i];System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- ");System.out.println("主题: " + getSubject(msg));System.out.println("发件⼈: " + getFrom(msg));System.out.println("收件⼈:" + getReceiveAddress(msg, null));System.out.println("发送时间:" + getSentDate(msg, null));System.out.println("是否已读:" + isSeen(msg));System.out.println("邮件优先级:" + getPriority(msg));System.out.println("是否需要回执:" + isReplySign(msg));System.out.println("邮件⼤⼩:" + msg.getSize() * 1024 + "kb");boolean isContainerAttachment = isContainAttachment(msg);System.out.println("是否包含附件:" + isContainerAttachment);if (isContainerAttachment) {saveAttachment(msg, "f:\\mailTest\\"+msg.getSubject() + "_"+i+"_"); //保存附件}StringBuffer content = new StringBuffer(30);getMailTextContent(msg, content);System.out.println("邮件正⽂:" + (content.length() > 100 ? content.substring(0,100) + "..." : content)); System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- "); System.out.println();}}/*** 解析邮件* @param messages 要解析的邮件列表*/public static void deleteMessage(Message ...messages) throws MessagingException, IOException {if (messages == null || messages.length < 1)throw new MessagingException("未找到要解析的邮件!");// 解析所有邮件for (int i = 0, count = messages.length; i < count; i++) {/*** 邮件删除*/Message message = messages[i];String subject = message.getSubject();// set the DELETE flag to truemessage.setFlag(Flags.Flag.DELETED, true);System.out.println("Marked DELETE for message: " + subject);}}/*** 获得邮件主题* @param msg 邮件内容* @return 解码后的邮件主题*/public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException { return MimeUtility.decodeText(msg.getSubject());}/*** 获得邮件发件⼈* @param msg 邮件内容* @return 姓名 <Email地址>* @throws MessagingException* @throws UnsupportedEncodingException*/public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {String from = "";Address[] froms = msg.getFrom();if (froms.length < 1)throw new MessagingException("没有发件⼈!");InternetAddress address = (InternetAddress) froms[0];String person = address.getPersonal();if (person != null) {person = MimeUtility.decodeText(person) + "";} else {person = "";}from = person + "<" + address.getAddress() + ">";return from;}/*** 根据收件⼈类型,获取邮件收件⼈、抄送和密送地址。
信息科学与工程学院09 届本科生毕业设计(论文)任务书学院信息科学与工程学院专业计算机科学与技术(师范)班级学号学生姓名指导教师一、论文题目基于Javamail的邮件收发系统二、内容和要求1.总体目标及性能(参数)要求(1)系统功能基本完善。
(2)系统具有良好的用户界面。
(3)系统具有较好的人机交互性、易于使用。
(4)系统可靠、稳定,具有一定的应用价值。
2.研究内容及拟采用的技术路线●研究内容:(1)邮件服务器的工作原理。
(2)DNS服务器的工作原理。
(3)SMTP、POP3、MIME协议。
(4)设计并实现基于Javamail的邮件收发系统,要求系统具有邮件接收、发送等基本功能。
●采用的技术路线:(1)开发工具采用Java+JavaMail API。
(2)数据库采用MySQL或SQL Server。
3.参考文献(10篇以上)[1] Java邮件开发详解。
张孝祥。
电子工业出版社,2007。
[2] Java高级程序设计。
王路群主编。
中国水利水电出版社, 2006 。
[3] Java课程设计。
黄明, 梁旭, 周绍斌编著。
电子工业出版社, 2006。
[4] Java开发与应用教程。
王吴迪, 赵枫朝等编著。
电子工业出版社, 2006。
[5] Java程序设计大学教程。
刘艺等编著。
机械工业出版社, 2006。
[6] Java数据库高级编程宝典。
陈天河编著。
电子工业出版社, 2005。
[7] Java程序设计与应用开发。
於东军等编著。
清华大学出版社, 2005。
[8] Java语言程序设计实训。
赵海廷主编。
武汉大学出版社, 2005。
[9] Java program design。
Cohoon, James P.,Davidson, Jack W。
McGraw-Hill Higher Education, 2004。
[10] Thinking in Java。
Eckel, Bruce。
Prentice Hall, c2000。
SpringBoot中利⽤JavaMailSender发送邮件的⽅法⽰例(附源码)快速⼊门在Spring Boot的⼯程中的pom.xml中引⼊spring-boot-starter-mail依赖:<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>如其他⾃动化配置模块⼀样,在完成了依赖引⼊之后,只需要在application.properties中配置相应的属性内容。
下⾯我们以QQ邮箱为例,在application.properties中加⼊如下配置(注意替换⾃⼰的⽤户名和密码):spring.mail.host=ername=⽤户名spring.mail.password=密码spring.mail.properties.mail.smtp.auth=truespring.mail.properties.mail.smtp.starttls.enable=truespring.mail.properties.mail.smtp.starttls.required=true通过单元测试来实现⼀封简单邮件的发送:@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(classes = Application.class)public class ApplicationTests {@Autowiredprivate JavaMailSender mailSender;@Testpublic void sendSimpleMail() throws Exception {SimpleMailMessage message = new SimpleMailMessage();message.setFrom("dyc87112@");message.setTo("dyc87112@");message.setSubject("主题:简单邮件");message.setText("测试邮件内容");mailSender.send(message);}}到这⾥,⼀个简单的邮件发送就完成了,运⾏⼀下该单元测试,看看效果如何?“由于Spring Boot的starter模块提供了⾃动化配置,所以在引⼊了spring-boot-starter-mail依赖之后,会根据配置⽂件中的内容去创建JavaMailSender实例,因此我们可以直接在需要使⽤的地⽅直接@Autowired来引⼊邮件发送对象。
开发一个简单的电子邮件客户端:实现收发邮件功能电子邮件客户端是一种用于收发电子邮件的应用程序或软件工具。
它通常具有用户界面,在其上用户可以编写、发送、接收、管理和存档电子邮件。
这些客户端可以在电脑、手机、平板电脑等设备上安装和使用。
在本文中,我将为您介绍如何开发一个简单的电子邮件客户端,实现收发邮件的基本功能。
这个客户端将使用简体中文编写,并提供齐全的用户界面和用户体验。
1.设计用户界面:首先,我们需要为电子邮件客户端设计一个用户界面。
界面应该简洁易用,并提供以下主要功能:-邮箱列表:显示用户的收件箱、发件箱、草稿箱、已发送等邮件类别。
-邮件列表:显示选定邮件类别中的邮件列表,包括发件人、主题、日期等信息。
-邮件预览:展示选定邮件的详细信息,包括发件人、主题、内容等。
-邮件撰写:用户可以在此处编写新的邮件,包括收件人、主题、内容等。
-邮件发送:用户可以点击发送按钮将邮件发送给收件人。
-邮件接收:客户端将定期检查服务器上是否有新邮件,并更新收件箱。
-邮件管理:用户可以对邮件进行管理操作,如删除、移动到其他文件夹等。
2.连接到邮件服务器:在开发电子邮件客户端之前,我们需要连接到一个邮件服务器。
可以选择使用现有的邮件服务器,如Gmail、Yahoo、163等,或者自己开发一个新的邮件服务器。
连接到邮件服务器需要使用远程通信协议,如POP3、IMAP、SMTP等。
- POP3(Post Office Protocol 3)是一种常用的电子邮件接收协议,用于从远程服务器接收邮件。
- IMAP(Internet Message Access Protocol)是另一种电子邮件接收协议,与POP3类似,但具有更强大的功能,如可以在多个设备上同步邮件、管理邮件夹等。
- SMTP(Simple Mail Transfer Protocol)是一种电子邮件发送协议,用于将邮件从客户端发送到服务器。
我们可以根据需求选择合适的协议,并使用相应的库或API连接到邮件服务器。
JavaMail通过IMAP和POP3接收未读以及设置已读邮件博客分类:javamailjavamailpop3imap使用javaMail收邮件主要有两种协议,一种是pop3,一种是imap。
这两种协议都可以用来收邮件,但是在其中的处理上是有区别的。
pop3是不支持判断邮件是否为已读的,也就是说你不能直接从收件箱里面取到未读邮件,这需要自己进行判断,然而imap就提供了这样的功能,使用imap时可以很轻松的判断该邮件是否为已读或未读或其他。
此外收件箱中的每一封邮件都对应着一个MessageNumber,所以可以通过一个MessageNumber拿到对应的那封邮件。
如:Message message =folder.getMessage(messageNumber);pop3和imap主要区别就是能否判断邮件状态的问题,其他的操作都差不多.pop3收邮件和解析邮件:Java代码1.package com.clxx.test;2.3.import java.io.FileOutputStream;4.import java.io.IOException;5.import java.io.InputStream;6.import java.io.OutputStream;7.import java.util.Enumeration;8.import java.util.Properties;9.10.import javax.mail.BodyPart;11.import javax.mail.Folder;12.import javax.mail.Message;13.import javax.mail.MessagingException;14.import javax.mail.Multipart;15.import javax.mail.Session;16.import javax.mail.Store;17.import javax.mail.internet.MimeMultipart;18.19.public class Email2 {20.21. public static void main(String args[]) throws MessagingException,22. IOException {23. Properties props = new Properties();24. props.setProperty("mail.store.protocol", "pop3");25. props.setProperty("mail.pop3.host", "");26. Session session = Session.getDefaultInstance(props);27. Store store = session.getStore("pop3");28. store.connect("username@", "password");29. Folder folder = store.getFolder("INBOX");30. folder.open(Folder.READ_WRITE);31.32. // 全部邮件数33. int messageCount = folder.getMessageCount();34. System.out.println(messageCount);35. Message[] messages = folder.getMessages();36. for (int i = 0; i < messages.length; i++) {37. Message message = messages[i];38. System.out.println(message.getSubject());39. // 删除邮件40. // message.setFlag(Flags.Flag.DELETED, true);41. // 标记为已读42. // message.setFlag(Flags.Flag.SEEN, true);43.44. //pop3没有判断邮件是否为已读的功能,要使用Imap才可以45. /*Flags flags = message.getFlags();46. if (flags.contains(Flags.Flag.SEEN))47. System.out.println("这是一封已读邮件");48. else {49. System.out.println("未读邮件");50. message.setFlag(Flags.Flag.SEEN, true);51. }*/52. System.out.println("发送时间:" + message.getSentDate());53. System.out.println("主题:" + message.getSubject());54. System.out.println("内容:" + message.getContent());55. //获取所有的Header,头信息56. Enumeration headers = message.getAllHeaders();57. System.out.println("----------------------allHeaders-----------------------------");58. /* while (headers.hasMoreElements()) {59. Header header = (Header)headers.nextElement();60. System.out.println(header.getName()+" ======= "+header.getValue());61. }*/62.63. //解析邮件内容64. Object content = message.getContent();65. if (content instanceof MimeMultipart) {66. MimeMultipart multipart = (MimeMultipart) content;67. parseMultipart(multipart);68. }69. System.out70. .println("========================================================");71. System.out72. .println("========================================================");73.74. }75.76. folder.close(true);77. store.close();78. }79.80. /**81. * 对复杂邮件的解析82. * @param multipart83. * @throws MessagingException84. * @throws IOException85. */86. public static void parseMultipart(Multipart multipart) throws MessagingException, IOException {87. int count = multipart.getCount();88. System.out.println("couont = "+count);89. for (int idx=0;idx<count;idx++) {90. BodyPart bodyPart = multipart.getBodyPart(idx);91. System.out.println(bodyPart.getContentType());92. if (bodyPart.isMimeType("text/plain")) {93. System.out.println("plain................."+bodyPart.getContent());94. } else if(bodyPart.isMimeType("text/html")) {95. System.out.println("html..................."+bodyPart.getContent());96. } else if(bodyPart.isMimeType("multipart/*")) {97. Multipart mpart = (Multipart)bodyPart.getContent();98. parseMultipart(mpart);99.100. } else if (bodyPart.isMimeType("application/oc tet-stream")) {101. String disposition = bodyPart.getDispositi on();102. System.out.println(disposition);103. if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) {104. String fileName = bodyPart.getFileName ();105. InputStream is = bodyPart.getInputStre am();106. copy(is, new FileOutputStream("D:\\"+f ileName));107. }108. }109. }110. }111.112. /**113. * 文件拷贝,在用户进行附件下载的时候,可以把附件的InputStream传给用户进行下载114. * @param is115. * @param os116. * @throws IOException117. */118. public static void copy(InputStream is, OutputStream o s) throws IOException {119. byte[] bytes = new byte[1024];120. int len = 0;121. while ((len=is.read(bytes)) != -1 ) {122. os.write(bytes, 0, len);123. }124. if (os != null)125. os.close();126. if (is != null)127. is.close();128. }129.}使用imap协议接收邮件:Java代码1.package com.clxx.test;2.3. import java.util.Properties;4.5. import javax.mail.Flags;6. import javax.mail.Folder;7. import javax.mail.Message;8. import javax.mail.Session;9.10. import com.sun.mail.imap.IMAPFolder;11. import com.sun.mail.imap.IMAPStore;12.13. /**14. * 使用imap协议获取未读邮件数15. *16. * @author w17. *18. */19. public class Email3 {20.21. public static void main(String[] args) throws Exception{22. String user = "username@";// 邮箱的用户名23. String password = "password"; // 邮箱的密码24.25. Properties prop = System.getProperties();26. prop.put("mail.store.protocol", "imap");27. prop.put("mail.imap.host", "");28.29. Session session = Session.getInstance(prop);30.31. int total = 0;32. IMAPStore store = (IMAPStore) session.getStore("imap"); // 使用imap会话机制,连接服务器33. store.connect(user, password);34. IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX"); // 收件箱35. folder.open(Folder.READ_WRITE);36. // 获取总邮件数37. total = folder.getMessageCount();38. System.out.println("-----------------共有邮件:" + total39. + " 封--------------");40. // 得到收件箱文件夹信息,获取邮件列表41. System.out.println("未读邮件数:" + folder.getUnreadMessageCount());42. Message[] messages = folder.getMessages();43. int messageNumber = 0;44. for (Message message : messages) {45. System.out.println("发送时间:" + message.getSentDate());46. System.out.println("主题:" + message.getSubject());47. System.out.println("内容:" + message.getContent());48. Flags flags = message.getFlags();49. if (flags.contains(Flags.Flag.SEEN))50. System.out.println("这是一封已读邮件");51. else {52. System.out.println("未读邮件");53. }54. System.out55. .println("========================================================");56. System.out57. .println("========================================================");58. //每封邮件都有一个MessageNumber,可以通过邮件的MessageNumber在收件箱里面取得该邮件59. messageNumber = message.getMessageNumber();60. }61. Message message = folder.getMessage(messageNumber);62. System.out.println(message.getContent()+message.getContentType());63. // 释放资源64. if (folder != null)65. folder.close(true);66. if (store != null)67. store.close();68. }69.70. }。
java利⽤springJavaMailSenderImpl发送邮件,⽀持普通⽂本、附件、。
博客分类:本⽂主要介绍利⽤发送邮件。
⾸先介绍了发送⼀般邮件,然后介绍了发送富⽂本(html)邮件及以velocity为模板发送邮件。
邮件发送分为为三步:创建邮件发送器、编写邮件、发送邮件。
Spring的提供了强⼤的邮件发送功能,可发送普通⽂本邮件、带附件邮件、html格式邮件、带图⽚邮件、设置发送内容编码格式、设置发送⼈的显⽰名称。
下⾯就进⾏介绍,⽰例代码中很多都是字符串硬编码,实际使⽤时推荐使⽤spring的配置⽂件进⾏配置。
1、创建邮件发送器⾸先定义对象,并对其进⾏smtp相关信息设置,相当于我们⾃⼰的邮箱,如下:Java代码1. JavaMailSenderImpl mailSender = new JavaMailSenderImpl();2. mailSender.setHost("");3. mailSender.setUsername("mosaic@");4. mailSender.setPassword("asterisks");JavaMailSenderImpl mailSender = new JavaMailSenderImpl();mailSender.setHost("");mailSender.setUsername("mosaic@");mailSender.setPassword("asterisks");当然更好的⽅法是使⽤配置⽂件进⾏配置,这⾥只是进⾏介绍,忽略硬编码先。
以上主机为邮箱服务商的smtp地址,⽤户名、密码为⽤户⾃⼰的邮箱。
除以上外还可以设置setPort(int port) 、setProtocol(String protocol) 等,可暂时不考虑。
毕业设计(论文)( 20 届)论文(设计)题目基于Javamail的邮件收发系统作者二级学院、专业班级指导教师(职称)论文字数论文完成时间20年月日基于JavaMail的邮件收发系统摘要电子邮件在当今社会中扮演了一个很重要的角色。
越来越多的人在使用它。
而且用它的人数势必会继续增加。
本文介绍了Javamail邮件收发系统的开发背景,对国内外现有的多种成熟的电子邮件系统进行分析和比较,总结出它们的优缺点,对Javamail技术进行深入研究,提出并设计实现了基于Javamail的邮件收发系统。
本系统利用SMTP协议和POP协议从底层进行开发,利用JavaMail API为收发邮件提供与协议无关的访问。
SMTP(简单邮件传输协议)是专门用来发送邮件的。
POP (邮局协议)是专门用于接收邮件的。
JavaMail API是一种可选的、能用于读取、编写和发送电子消息的标准扩展包。
本文主要可分为四个部分。
第一部分介绍了Javamail邮件系统的意义和现状。
第二部分具体介绍了几种相关协议和Javamail API。
第三部分主要介绍了系统的开发工具JA V A语言、Eclipse及其安装过程与配置方法。
第四部分详细阐述了Javamail邮件收发系统的实现过程。
关键词:SMTP,POP,JA V AMAIL,邮件收发MAIL SYSTEM BASED ON JAVAMAILABSTRACTE-Mail play a very important role in modern times. More and more people are using it, and the number of it will larger and larger. This paper introduced the javamail system's development background, analyzed and compared some existing maturity Email system at home and abroad , summarized their advantages and disadvantages, studied deeply with the javamail technology , proposed and designed out the mail system based on javamail. This system used POP protocol and SMTP protocol to develop from the bottom, used JavaMail API to provide the visit which has nothing to do with the agreement for send and receive email. SMTP (Simple Mail Transfer Protocol) is designed to send a message. POP (Post Office Protocol) is designed to receive mail. JavaMail API is an standard expansion package which is optional, can be used to read, write and send electronic messages.This paper can be divided into four parts. The first part introduced javamail email system's significance and status. The second part introduced several related agreements and JavaMail API. The third part mainly introduced system's development tools JA V A language , Eclipse and their installation process and configuration method. The fourth part detailed javamail email system's realization process.Keywords:SMTP, POP, JA V AMAIL, Email to send and receive目录第一章绪论 (1)1.1电子邮件介绍 (1)1.2研究意义 (1)1.3研究现状 (3)第二章相关邮件协议和JavaMail API (5)2.1相关邮件协议 (5)2.2JavaMail API (6)2.2.1 JavaMail API简介 (6)2.2.2 JavaMail API核心类 (6)2.3.3 JavaMail API的应用 (8)第三章应用系统开发工具 (10)3.1Java开发语言简介 (11)3.2开发工具Eclipse (12)3.3开发软件的安装 (12)3.3.1 JA V A环境的安装与配置 (12)3.3.2 Eclipse的安装 (14)3.3.3 javamail的安装 (15)第四章JavaMail系统的实现 (16)4.1环境配置与界面搭建 (16)4.2设置邮件服务器参数的实现 (16)4.3创建与发送邮件功能的实现 (17)4.3.1 装载邮件服务器属性, 并与其建立连接 (17)4.3.2 构建邮件 (18)4.3.3 创建Transport对象发送邮件 (19)4.4接收邮件功能的实现 (20)4.4.1 获取服务器信息 (20)4.4.2 建立通信连接 (20)4.4.3显示邮件 (20)4.5删除邮件功能的实现 (22)第五章结语 (23)参考文献 (24)致谢 (25)第一章绪论本文是一项基于JavaMail的邮件系统的综合性研究,使用Sun公司提供的JavaMail API实现电子邮件的发送、电子邮件的接收等等功能。
Java实现读取163邮箱,qq邮箱的邮件内容通过使⽤java mail来实现读取163邮箱,qq邮箱的邮件内容。
1.代码实现创建springboot项⽬,引⼊依赖包<!--mail--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency>实现类import com.sun.mail.imap.IMAPFolder;import com.sun.mail.imap.protocol.IMAPProtocol;import org.apache.tomcat.util.http.fileupload.IOUtils;import org.springframework.util.ObjectUtils;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeUtility;import java.io.*;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.*;public class ShowMail {public static String NORM_DATETIME_PATTERN = "yyyy-MM-dd hh:mm:ss";private MimeMessage mimeMessage;/*** 附件下载后的存放⽬录*/private String saveAttachPath = "";/*** 存放邮件内容的StringBuffer对象*/private StringBuffer bodyText = new StringBuffer();/*** 构造函数,初始化⼀个MimeMessage对象** @param mimeMessage*/public ShowMail(MimeMessage mimeMessage) {this.mimeMessage = mimeMessage;}/*** 获得发件⼈的地址和姓名** @return* @throws MessagingException*/public String getFrom() throws MessagingException {InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();String from = address[0].getAddress();if (from == null) {from = "";}String personal = address[0].getPersonal();if (personal == null) {personal = "";}String fromAddr = null;if (personal != null || from != null) {fromAddr = personal + "<" + from + ">";}return fromAddr;}/*** 获得邮件的收件⼈,抄送,和密送的地址和姓名,根据所传递的参数的不同** @param type "to"----收件⼈ "cc"---抄送⼈地址 "bcc"---密送⼈地址* @return* @throws MessagingException* @throws UnsupportedEncodingException*/public String getMailAddress(String type) throws MessagingException, UnsupportedEncodingException { if (ObjectUtils.isEmpty(type)) {return "";}String addType = type.toUpperCase();if (!addType.equals("TO") && !addType.equals("CC") && !addType.equals("BCC")) {return "";}InternetAddress[] address;if (addType.equals("TO")) {address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);} else if (addType.equals("CC")) {address = (InternetAddress[]) mimeMessage.getRecipients();} else {address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);}if (ObjectUtils.isEmpty(address)) {return "";}StringBuilder mailAddr = new StringBuilder();String emailAddr;String personal;for (int i = 0; i < address.length; i++) {emailAddr = address[i].getAddress();if (emailAddr == null) {emailAddr = "";} else {emailAddr = MimeUtility.decodeText(emailAddr);}personal = address[i].getPersonal();if (personal == null) {personal = "";} else {personal = MimeUtility.decodeText(personal);}mailAddr.append(",").append(personal).append("<").append(emailAddr).append(">");}return mailAddr.toString().substring(1);}/*** 获得邮件主题** @return* @throws MessagingException* @throws UnsupportedEncodingException*/public String getSubject() throws MessagingException, UnsupportedEncodingException {String subject = MimeUtility.decodeText(mimeMessage.getSubject());if (subject == null) {subject = "";}return subject;}/*** 获得邮件发送⽇期** @return* @throws MessagingException*/public String getSentDate() throws MessagingException {Date sentDate = mimeMessage.getSentDate();SimpleDateFormat format = new SimpleDateFormat(NORM_DATETIME_PATTERN);return format.format(sentDate);}/*** 获得邮件正⽂内容** @return*/public String getBodyText() {return bodyText.toString();}/*** 解析邮件,把得到的邮件内容保存到⼀个StringBuffer对象中,解析邮件* 主要是根据MimeType类型的不同执⾏不同的操作,⼀步⼀步的解析* @param part* @throws MessagingException* @throws IOException*/public void getMailContent(Part part) throws MessagingException, IOException {String contentType = part.getContentType();int nameIndex = contentType.indexOf("name");boolean conName = false;if (nameIndex != -1) {conName = true;}if (part.isMimeType("text/plain") && conName == false) {bodyText.append((String) part.getContent());} else if (part.isMimeType("text/html") && conName == false) {bodyText.append((String) part.getContent());} else if (part.isMimeType("multipart/*")) {Multipart multipart = (Multipart) part.getContent();int counts = multipart.getCount();for (int i = 0; i < counts; i++) {this.getMailContent(multipart.getBodyPart(i));}} else if (part.isMimeType("message/rfc822")) {this.getMailContent((Part) part.getContent());}}/*** 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"** @return* @throws MessagingException*/public boolean getReplySign() throws MessagingException {boolean replySign = false;String needReply[] = mimeMessage.getHeader("Disposition-Notification-To");if (needReply != null) {replySign = true;}return replySign;}/*** 判断此邮件是否已读,如果未读返回false,反之返回true** @return* @throws MessagingException*/public boolean isNew() throws MessagingException {boolean isNew = false;Flags flags = mimeMessage.getFlags();Flags.Flag[] flag = flags.getSystemFlags();for (int i = 0; i < flag.length; i++) {if (flag[i] == Flags.Flag.SEEN) {isNew = true;}}return isNew;}/*** 判断此邮件是否包含附件** @param part* @return* @throws MessagingException* @throws IOException*/public boolean isContainAttach(Part part) throws MessagingException, IOException { boolean attachFlag = false;if (part.isMimeType("multipart/*")) {Multipart mp = (Multipart) part.getContent();BodyPart mPart;String conType;for (int i = 0; i < mp.getCount(); i++) {mPart = mp.getBodyPart(i);String disposition = mPart.getDisposition();if (Part.ATTACHMENT.equals(disposition) || Part.INLINE.equals(disposition)) {} else if (mPart.isMimeType("multipart/*")) {attachFlag = this.isContainAttach(mPart);} else {conType = mPart.getContentType();if (conType.toLowerCase().indexOf("application") != -1 || conType.toLowerCase().indexOf("name") != -1){ attachFlag = true;}}}} else if (part.isMimeType("message/rfc822")) {attachFlag = isContainAttach((Part) part.getContent());}return attachFlag;}/*** 保存附件** @param part* @throws MessagingException* @throws IOException*/public void saveAttachMent(Part part) throws MessagingException, IOException {String fileName;if (part.isMimeType("multipart/*")) {Multipart mp = (Multipart) part.getContent();BodyPart mPart;for (int i = 0; i < mp.getCount(); i++) {mPart = mp.getBodyPart(i);String disposition = mPart.getDisposition();if (Part.ATTACHMENT.equals(disposition) || Part.INLINE.equals(disposition)) {fileName = mPart.getFileName();if (null != fileName && fileName.toLowerCase().indexOf("gb2312") != -1) {fileName = MimeUtility.decodeText(fileName);}this.saveFile(fileName, mPart.getInputStream());} else if (mPart.isMimeType("multipart/*")) {this.saveAttachMent(mPart);} else {fileName = mPart.getFileName();if ((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)) {fileName = MimeUtility.decodeText(fileName);this.saveFile(fileName, mPart.getInputStream());}}}} else if (part.isMimeType("message/rfc822")) {this.saveAttachMent((Part) part.getContent());}}/*** 设置附件存放路径** @param attachPath*/public void setAttachPath(String attachPath) {this.saveAttachPath = attachPath;}/*** 获得附件存放路径** @return*/public String getAttachPath() {return saveAttachPath;}/*** 真正的保存附件到指定⽬录⾥** @param fileName* @param in* @throws IOException*/private void saveFile(String fileName, InputStream in) throws IOException {String osName = System.getProperty("");String storeDir = this.getAttachPath();if (null == osName) {osName = "";}if (osName.toLowerCase().indexOf("win") != -1) {if (ObjectUtils.isEmpty(storeDir))} else {storeDir = "/tmp";}// fileName=fileName.replace("=?", "");// fileName=fileName.replace("?=", "");// fileName = fileName.substring(fileName.length() - 6, fileName.length());FileOutputStream fos = new FileOutputStream(new File(storeDir + File.separator + fileName));IOUtils.copy(in, fos);IOUtils.closeQuietly(fos);IOUtils.closeQuietly(in);}/*** 获取163邮箱信息** @param host* @param username* @param password* @param protocol* @return* @throws MessagingException*/public static Message[] getWEMessage(String host, String username, String password, String protocol) throws MessagingException { //创建属性对象Properties props = System.getProperties();props.setProperty("mail.store.protocol", protocol);//创建会话Session session = Session.getDefaultInstance(props, null);//存储对象Store store = session.getStore(protocol);//连接store.connect(host, username, password);//创建⽬录对象Folder folder = store.getFolder("INBOX");if (folder instanceof IMAPFolder) {IMAPFolder imapFolder = (IMAPFolder)folder;//javamail中使⽤id命令有校验checkOpened, 所以要去掉id⽅法中的checkOpened();imapFolder.doCommand(new IMAPFolder.ProtocolCommand() {public Object doCommand(IMAPProtocol p) throws com.sun.mail.iap.ProtocolException {p.id("FUTONG");return null;}});}if(folder != null) {folder.open(Folder.READ_WRITE);}return folder.getMessages();}/*** 获取qq邮箱信息** @param host* @param username* @param password* @param protocol* @return* @throws MessagingException*/public static Message[] getQQMessage(String host, String username, String password, String protocol) throws MessagingException { //创建属性对象Properties props = new Properties();props.put("mail.store.protocol", protocol);//创建会话Session session = Session.getDefaultInstance(props, null);//存储对象Store store = session.getStore(protocol);//连接store.connect(host,username,password);//创建⽬录对象Folder folder = store.getFolder("Inbox");if(folder != null) {folder.open(Folder.READ_WRITE);}return folder.getMessages();}/*** 过滤邮箱信息** @param messages* @param fromMail 只读取该邮箱发来的邮件,如果为空则不过滤* @param startDate 只读取该⽇期以后的邮件,如果为空则不过滤* @return* @throws MessagingException*/public static List<Message> filterMessage(Message[] messages, String fromMail, String startDate) throws MessagingException, ParseException {List<Message> messageList = new ArrayList<>();if (ObjectUtils.isEmpty(messages)) {return messageList;}boolean isEnptyFromMail = ObjectUtils.isEmpty(fromMail);boolean isEnptyStartDate = ObjectUtils.isEmpty(startDate);if (isEnptyFromMail && isEnptyStartDate) {return Arrays.asList(messages);}String from;for (Message message: messages) {from = null;if(message.getFrom() != null) {from = (message.getFrom()[0]).toString();}if (isEnptyFromMail) {if (message.getSentDate() != null && new SimpleDateFormat(NORM_DATETIME_PATTERN).parse(startDate).getTime() > message.getSentDate().getTime()) { continue;}} else if (null != from && from.contains(fromMail)) {if (!isEnptyStartDate && new SimpleDateFormat(NORM_DATETIME_PATTERN).parse(startDate).getTime() > message.getSentDate().getTime()) {continue;}} else {continue;}messageList.add(message);}return messageList;}/*** 打印邮件** @param messageList* @throws IOException* @throws MessagingException*/public static void printMailMessage(List<Message> messageList) throws IOException, MessagingException {System.out.println("邮件数量:" + messageList.size());ShowMail re;Message message;for (int i = 0, leng = messageList.size(); i < leng; i++) {message = messageList.get(i);re = new ShowMail((MimeMessage) message);System.out.println("邮件【" + i + "】主题:" + re.getSubject());System.out.println("邮件【" + i + "】发送时间:" + re.getSentDate());System.out.println("邮件【" + i + "】是否需要回复:" + re.getReplySign());System.out.println("邮件【" + i + "】是否已读:" + re.isNew());System.out.println("邮件【" + i + "】是否包含附件:" + re.isContainAttach( message));System.out.println("邮件【" + i + "】发送⼈地址:" + re.getFrom());System.out.println("邮件【" + i + "】收信⼈地址:" + re.getMailAddress("to"));System.out.println("邮件【" + i + "】抄送:" + re.getMailAddress("cc"));System.out.println("邮件【" + i + "】暗抄:" + re.getMailAddress("bcc"));System.out.println("邮件【" + i + "】发送时间:" + re.getSentDate());System.out.println("邮件【" + i + "】邮件ID:" + ((MimeMessage) message).getMessageID());re.getMailContent(message);System.out.println("邮件【" + i + "】正⽂内容:\r\n" + re.getBodyText());re.setAttachPath("D:\\Download\\mailFile\\");re.saveAttachMent(message);}}public static void main(String[] args) throws MessagingException, IOException, ParseException {//163登录信息//邮件服务器String host = "";//邮箱账号String username = "xx";//授权码String password = "yy";//协议String protocol = "imaps";//只读取该邮箱发来的邮件String fromMail = null;//只读取该⽇期以后的邮件String startDate = null;List<Message> messageList = filterMessage(getWEMessage(host, username, password, protocol), fromMail, startDate);printMailMessage(messageList);String host2 = "";String username2 = "xx";String password2 = "yy";// String protocol2 = "imaps";String protocol2 = "pop3";String fromMail2 = null;String startDate2 = null;List<Message> messageList2 = filterMessage(getQQMessage(host2, username2, password2, protocol2), fromMail2, startDate2); printMailMessage(messageList2);}}2.配置授权码163邮箱:qq邮箱:3.实现效果:运⾏main⽅法,查看控制台:邮件数量:xx邮件【0】主题:欢迎您使⽤xx邮箱!邮件【0】发送时间:xx邮件【0】是否需要回复:false邮件【0】是否已读:true邮件【0】是否包含附件:false邮件【0】发送⼈地址:xx邮件【0】收信⼈地址:xx邮件【0】抄送:邮件【0】暗抄:邮件【0】发送时间:xx邮件【0】邮件ID:xx邮件【0】正⽂内容:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>欢迎使⽤</title><style>body, div, p, img {padding: 0;margin: 0;font-family: 'Microsoft Yahei', "PingFang SC", "Hiragino Sans GB", "wenquanyi micro hei", Arial, Helvetica, "STHeiti", sans-serif; }.contain {width: 700px;margin: 0 auto;font-size: 0;}.wrap {position: relative;}.wrap .welcome {position: absolute;width: 290px;left: 75px;top: 100px;font-size: 18px;color: #fff;line-height: 32px;font-weight: 500;}.wrap .welcome p.indentation {font-size: 16px;font-weight: normal;}.wrap a {position: absolute;display: block;width: 104px;height: 39px;}.wrap a.mobile{left: 501px;top: 434px;}left: 501px;top: 485px;}</style></head><body><div class="contain"><div class="wrap"><div class="welcome"><p class="indentation-title">尊敬的xx:</p><p class="indentation">您好,您的邮箱已开通。
第25卷第3期 计算机应用与软件Vo l 25No .32008年3月 Co m puter Applicati o ns and Soft w are M ar .2008使用JavaM ail/J AF 开发中文邮件系统的关键技术研究袁梅冷 聂 哲(深圳职业技术学院软件工程系 广东深圳518055)收稿日期:2006-04-13。
袁梅冷,讲师,主研领域:J 2EE 技术,电子商务等。
摘 要 Java M ail 提供了对邮件收发核心流程很好的支持,但在开发实用邮件系统过程中,必然会遇到Java M a il 本身并不支持的如嵌套邮件内容解释、M I M E 类型数据处理框架结构、中文乱码等技术难题。
在全面研究基于Java 技术的邮件系统开发的基础上,给出了通用的解决方案和实现要点。
关键词Java M ail J AF 中文乱码 邮件系统RES EARCH ON THE KEY TEC HNOLOG I ES IN THE DEVELOPM ENTOF CH INES E E MA IL S YSTEM BASED ON J AVAMA IL AND J AFYuanM eileng N ie Zhe(D e part m ent of S oft w are Engineeri ng,Colle g e of Sh e nzh e n P ol y t echnic ,Sh e nzhen 518055,Guangdong,China )Abstrac t Java M a il facilita tes the deve l op m en t o f E m ail Sy stem .H ow eve r ,during the develop m ent o f practi ca l E m a il syste m,so m e proble m s such as t he pars i ng o f nesti ng e m a il content ,t he process fra m ework o f data o fM I M E type ,and the unreadab le Ch i nese cha rs can not be supported by Java M a i.l G enera l so l utions to t hese prob l em s are presented ,and the key techno l og i es are prov i ded .K eywordsJava M ail JavaBeans A cti vation Fra m ewo rk(J A F) U nreadable ch i nese cha rs E m ail syste m0 引 言Java 语言作为一种强大的网络编程语言,为支持邮件系统的开发推出了Java M ail 开发包,极大地简化了基于Java 技术的邮件系统的开发。
Java 收取和发送邮件+SSL这里使用Gmail 邮箱测试1. 收取邮件[java] view plaincopypackage lius.javamail.ssl; import java.io.UnsupportedEncodingException; importjava.security.*; import java.util.Properties; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeUtility; /** * 用于收取Gmail邮件* @author Winter Lau */ public class GmailFetch { public static void main(Stringargv[]) throws Exception { Security.addProvider(new .ssl.internal.ssl.Provider()); final String SSL_FACTORY = ".ssl.SSLSocketFactory";// Get a Properties object Properties props = System.getProperties();props.setProperty("mail.pop3.socketFactory.class",SSL_FACTORY);props.setProperty("mail.pop3.socketFactory.fallback", "false"); props.setProperty("mail.pop3.port", "995"); props.setProperty("mail.pop3.socketFactory.port", "995"); //以下步骤跟一般的JavaMail操作相同Session session = Session.getDefaultInstance(props,null); //请将红色部分对应替换成你的邮箱帐号和密码URLName urln = newURLName("pop3","",995,null, "邮箱帐号", "邮箱密码"); Store store =session.getStore(urln); Folder inbox = null; try { store.connect(); inbox =store.getFolder("INBOX");inbox.open(Folder.READ_ONLY); FetchProfile profile = new FetchProfile();profile.add(FetchProfile.Item.ENVELOPE);Message[] messages = inbox.getMessages();inbox.fetch(messages, profile); System.out.println("收件箱的邮件数:" + messages.length); for (int i = 0;i < messages.length; i++) { //邮件发送者String from =decodeText(messages[i].getFrom()[0].toString()); InternetAddress ia = new InternetAddress(from); System.out.println("FROM:" +ia.getPersonal()+'('+ia.getAddress()+')'); //邮件标题System.out.println("TITLE:" +messages[i].getSubject()); //邮件大小System.out.println("SIZE:" + messages[i].getSize());//邮件发送时间System.out.println("DATE:" + messages[i].getSentDate()); } } finally{ try { inbox.close(false); } catch (Exception e) {} try { store.close(); } catch (Exception e) {} } } protected static String decodeText(String text) throws UnsupportedEncodingException { if (text == null) return null; if (text.startsWith("=?GB") ||text.startsWith("=?gb")) text =MimeUtility.decodeText(text); else text = new String(text.getBytes("ISO8859_1")); returntext; } }2.发送邮件[java] view plaincopypackage lius.javamail.ssl; import java.security.Security; import java.util.Date; import java.util.Properties; importjavax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; importjavax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; importjavax.mail.internet.MimeMessage; /** * 使用Gmail 发送邮件* @author Winter Lau */ public class GmailSender { public static void main(String[] args) throws AddressException, MessagingException{ Security.addProvider(new.ssl.internal.ssl.Provider()); final String SSL_FACTORY = ".ssl.SSLSocketFactory";// Get a Properties object Properties props = System.getProperties();props.setProperty("mail.smtp.host", ""); props.setProperty("mail.smtp.socketFactory.class",SSL_FACTORY);props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.auth", "true"); final String username = "邮箱帐号"; final String password = "邮箱密码"; Session session =Session.getDefaultInstance(props, newAuthenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return newPasswordAuthentication(username,password); }}); // -- Create a new message -- Message msg = newMimeMessage(session); // -- Set the FROM and TO fields -- msg.setFrom(newInternetAddress(username + "@"));msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[收件人地址]",false));msg.setSubject("Hello"); msg.setText("How are you"); msg.setSentDate(new Date());Transport.send(msg); System.out.println("Message sent."); } }现在发送邮件时会发生异常信息,如下:.ssl.SSLHandshakeException:sun.security.validator.ValidatorException: PKIX path building failed:sun.security.provider.certpath.SunCertPathBuilderExcepti on: unable to find valid certification path to requested targetatorg.springframework.mail.javamail.JavaMailSenderImpl.do Send(JavaMailSenderImpl.java:419)atorg.springframework.mail.javamail.JavaMailSenderImpl.se nd(JavaMailSenderImpl.java:342)Caused by: javax.mail.MessagingException: Exception reading response;nested exception is:.ssl.SSLHandshakeException:sun.security.validator.ValidatorException: PKIX path building failed:sun.security.provider.certpath.SunCertPathBuilderExcepti on: unable to find valid certification path to requested targetatcom.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1462)atcom.sun.mail.smtp.SMTPTransport.openServer(SMTPTra nsport.java:1260)... 4 moreCaused by: .ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed:sun.security.provider.certpath.SunCertPathBuilderExcepti on: unable to find valid certification path to requested targetat.ssl.internal.ssl.Alerts.getSSLException(Alerts. java:174)at.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSock etImpl.java:1611)at.ssl.internal.ssl.Handshaker.fatalSE(Handsha ker.java:187)... 8 moreCaused by: sun.security.validator.ValidatorException: PKIX path building failed:sun.security.provider.certpath.SunCertPathBuilderExcepti on: unable to find valid certification path to requested targetatsun.security.validator.PKIXValidator.doBuild(PKIXValidato r.java:285)atsun.security.validator.PKIXValidator.engineValidate(PKIX Validator.java:191)atsun.security.validator.Validator.validate(Validator.java:218 )at.ssl.internal.ssl.X509TrustManagerImpl.validat e(X509TrustManagerImpl.java:126)at.ssl.internal.ssl.X509TrustManagerImpl.check ServerTrusted(X509TrustManagerImpl.java:209)... 20 moreCaused by:sun.security.provider.certpath.SunCertPathBuilderExcepti on: unable to find valid certification path to requested targetatsun.security.provider.certpath.SunCertPathBuilder.engine Build(SunCertPathBuilder.java:174)atjava.security.cert.CertPathBuilder.build(CertPathBuilder.ja va:238)atsun.security.validator.PKIXValidator.doBuild(PKIXValidato r.java:280)... 26 more原因是需要保存安装证书官方的QA/products/javamail/FAQ.html#installcertQ: When connecting to my mail server over SSL I get an exception like "unable to find valid certification path to requested target".A: Your server is probably using a test certificate or self-signed certificate instead of a certificate signed by a commercial Certificate Authority. You'll need to install the server's certificate into your trust store. TheInstallCert program will help.使用DOS命令进入InstallCert.java 存放目录运行javac InstallCert.java 将InstallCert.java 编译成 .class文件在运行java InstallCert :465【其中xyz是要使用的mail,例如:】【465是端口号】得到jssecacerts文件后复制到jdk1.6.0_14\jre\lib\security 目录然后再发送邮件就OK了代码都是测试过的,运行没问题。
JavaMail(JAVA邮件服务) API详解一、JavaMail API简介JavaMail API是读取、撰写、发送电子信息的可选包。
我们可用它来建立如Eudora、Foxmail、MS Outlook Express一般的邮件用户代理程序(Mail User Agent,简称MUA)。
而不是像sendmail或者其它的邮件传输代理(Mail Transfer Agent,简称MTA)程序那样可以传送、递送、转发邮件。
从另外一个角度来看,我们这些电子邮件用户日常用MUA程序来读写邮件,而MUA依赖着MTA处理邮件的递送。
在清楚了到MUA与MTA之间的关系后,让我们看看JavaMail API是如何提供信息访问功能的吧!JavaMail API被设计用于以不依赖协议的方式去发送和接收电子信息,这个API被分为两大部分:基本功能:如何以不依赖于协议的方式发送接收电子信息,这也是本文所要描述的,不过在下文中,大家将看到这只是一厢情愿而已。
第二个部分则是依赖特定协议的,比如SMTP、POP、IMAP、NNTP协议。
在这部分的JavaMail API是为了和服务器通讯,并不在本文的内容中。
二、相关协议一览在我们步入JavaMail API之前,先看一下API所涉及的协议。
以下便是大家日常所知、所乐于使用的4大信息传输协议:SMTPPOPIMAPMIME当然,上面的4个协议,并不是全部,还有NNTP和其它一些协议可用于传输信息,但是由于不常用到,所以本文便不提及了。
理解这4个基本的协议有助于我们更好的使用JavaMail API。
然而JavaMail API是被设计为与协议无关的,目前我们并不能克服这些协议的束缚。
确切的说,如果我们使用的功能并不被我们选择的协议支持,那么JavaMail API并不可能如魔术师一样神奇的赋予我们这种能力。
1.SMTP简单邮件传输协议定义了递送邮件的机制。
在下文中,我们将使用基于Java-Mail的程序与公司或者ISP的SMTP服务器进行通讯。
package com.neusoft.mail;import javax.mail.*;import java.io.*;import java.text.*;import java.util.*;import java.util.Enumeration;public class GetMail {String POP3Host=""; //POP3服?器String mailServerPort="110";//POP3服?器端口号String user=""; //登?POP3服?器的?号String password=""; //登?POP3服?器的密?boolean validate = true;//是否需要身???Session session = null;Folder folder = null;Store store = null;//无参数的?造函数public GetMail() {}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getPOP3Host() {return POP3Host;}public void setPOP3Host(String host) {POP3Host = host;}public String mailServerPort() {return mailServerPort;}public void mailServerPort(String mailServerPort) { this.mailServerPort = mailServerPort;}public String getUser() {return user;}public void setUser(String user) {er = user;}public boolean isValidate() {return validate;}public void setValidate(boolean validate) {this.validate = validate;}//?接?件服?器public void connect() throws Exception{//?建一个授????象POP3Auth auth = new POP3Auth();auth.setAccount(user,password);//取得一个Session?象Properties prop=new Properties();prop.put("mail.pop3.host",POP3Host);prop.put("mail.pop3.port", this.mailServerPort);prop.put("mail.pop3.auth", validate ? "true" : "false");session = Session.getDefaultInstance(prop,auth);//取得一个Store?象store = session.getStore("pop3");store.connect(POP3Host,user,password);//取得一个Folder?象folder=store.getDefaultFolder().getFolder("INBOX");folder.open(Folder.READ_ONLY);}//?得所有?件的列表public Message[] getAllMail() throws Exception{//建立POP3?接connect();//取得所有的Message?象Message[] msg=folder.getMessages();FetchProfile profile=new FetchProfile();profile.add(FetchProfile.Item.ENVELOPE);folder.fetch(msg,profile);return msg;}//取得?件列表的信息public List getMailInfo(Message[] msg) throws Exception{List result = new ArrayList();Map map = null;Multipart mp = null;BodyPart part = null;String disp = null;SimpleDateFormat fmt = new SimpleDateFormat("yyyy年MM月dd日hh:mm:ss");Enumeration enum1 = null;//取出?个?件的信息for (int i=0;i<msg.length;i++){map = new HashMap();//?取?件IDenum1 = msg[i].getAllHeaders();Header h = null;while (enum1.hasMoreElements()){h = (Header)enum1.nextElement();if (h.getName().equals("Message-ID")){map.put("ID",h.getValue());}}//?取?件??map.put("subject",msg[i].getSubject());//?取?件人map.put("sender",msg[i].getFrom()[0].toString());//?取?件?送日期//map.put("senddate",fmt.getInstance().format(msg[i].getSentDate()));//?取?件大小map.put("size",new Integer(msg[i].getSize())+" K");map.put("hasAttach"," ");//判断是否有附件if(msg[i].isMimeType("multipart/*")){mp=(Multipart)msg[i].getContent();//遍??个Miltipart?象for (int j=0;j<mp.getCount();j++){part = mp.getBodyPart(j);disp = part.getDisposition();//如果有附件if(disp!=null && (disp.equals(Part.ATTACHMENT)||disp.equals(Part.INLINE))){//?置有附件的特征?map.put("hasAttach","√");}}}result.add(map);}return result;}//?找指定?件public Message findMail(String id) throws Exception{Message[] msg = getAllMail();Enumeration enum1 = null;Header h = null;for (int i=0;i<msg.length;i++){enum1 = msg[i].getAllHeaders();//?找?件?中的Message-ID?while (enum1.hasMoreElements()){h = (Header)enum1.nextElement();//根据?入的message-id来?找目??件if ((h.getName().equals("Message-ID"))&&(h.getValue().equals(id))){ return msg[i];}}}return null;}//?取?件内容public Map readMail(String basePath,String id) throws Exception{ Map map = new HashMap();//找到目??件Message msg = findMail(id);//?取?件??map.put("subject",msg.getSubject());//?取?件人map.put("sender",msg.getFrom()[0].toString());map.put("attach","");//取得?件内容if (msg.isMimeType("text/*")){map.put("content",msg.getContent().toString());}else{StringBuffer result = new StringBuffer();Multipart mp=(Multipart)msg.getContent();BodyPart part = null;String disp = null;//遍??个Miltipart?象for (int j=0;j<mp.getCount();j++){part = mp.getBodyPart(j);disp = part.getDisposition();//如果有附件if(disp!=null && (disp.equals(Part.ATTACHMENT)||disp.equals(Part.INLINE))){//取得附件文件名String filename = part.getFileName();filename = new String(filename.getBytes("ISO8859-1"),"gb2312");map.put("attach",filename);//下?附件InputStream in=part.getInputStream();filename = basePath + "/"+filename;FileOutputStream out=new FileOutputStream(new File(filename));byte[] content=new byte[255];int read=0;while((read=in.read(content))!=-1){out.write(content);}out.close();in.close();}else{result.append(part.getContent().toString());}}map.put("content",result.toString());}return map;}//定?一个POP3授????static class POP3Auth extends Authenticator{String user;String password;//?置?号信息void setAccount(String user,String password){er = user;this.password = password;}//取得PasswordAuthentication?象protected PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(user,password);}}}。