使用javaxMail接收邮件

1、引入maven依赖

        <dependency><groupId>javax.mail</groupId><artifactId>javax.mail-api</artifactId><version>1.6.2</version></dependency><dependency><groupId>com.sun.mail</groupId><artifactId>javax.mail</artifactId><version>1.6.2</version></dependency>

2、准备好相关配置信息

email:#邮件协议类型、账号、密码imapserver: pop3.hn.sgcc.com.cnusername: xxxxx@163.compassword: xxxxxx

3、邮件解析类

public class ReceiveMail{/**** 接收邮件**/public static void receiveEmail(){Properties properties = null;Folder folder = null;try {properties = new Properties();properties.setProperty("mail.store.protocol", "pop3");properties.setProperty("mail.pop3.host", imapserver);properties.setProperty("mail.pop3.port", "110");Session session = Session.getDefaultInstance(properties , null);Store store = session.getStore("pop3");store.connect(imapserver,username,password);folder = store.getFolder("inbox");folder.open(Folder.READ_WRITE);//获取收件箱中的所有邮件//            Message[] messages = folder.getMessages();//只获取前N(beforeDay)天内的邮件Date dateBefore = DateUtils.getDateBefore(new Date(), beforeDay);SearchTerm searchTerm = new SentDateTerm(DateTerm.GE, dateBefore);SentDateTerm sentDateTerm = new SentDateTerm(DateTerm.LT, new Date());SearchTerm searchTermAnd = new AndTerm(searchTerm, sentDateTerm);Message[] messages = folder.search(searchTermAnd);SimpleDateFormat format = new SimpleDateFormat(DateUtils.yyyyMMddHHmmss);System.out.println("messages = " + messages.length);int i = 0 ;for (Message message : messages) {i++;System.out.println("第" + i + "封邮件,当前时间的前" + beforeDay + "天:" + format.format(dateBefore));//获取邮件的状态Flags flags = message.getFlags();//获取未读的邮件内容if (!flags.contains(Flags.Flag.SEEN)) {//将接收到的邮件附件存储到指定目录下,输出邮件的其他相关信息getFileInputStream(message);//将邮件设置为已读状态,对于pop3不生效message.setFlag(Flags.Flag.SEEN, true);}}}catch (Exception e){e.printStackTrace();}}/**** 将接收到的邮件中附件储存到指定位置并输出邮件的其他相关信息**/	public void getFileInputStream(Part part) throws Exception {Message message = (Message) part;if (part.isMimeType("multipart/*")) {Multipart multipart = (Multipart) part.getContent();UUID format = UUID.randomUUID();for (int i = 0; i < multipart.getCount(); i++) {BodyPart bodyPart = multipart.getBodyPart(i);String disposition = bodyPart.getDisposition();String fileName = null;//说明有附件if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) {fileName = bodyPart.getFileName();if (null == fileName || fileName.length() <= 0) {continue;}if ((fileName != null)) {fileName = MimeUtility.decodeText(fileName);}String fsr = message.getFrom()[0].toString();fsr = fsr.substring(fsr.indexOf("<") + 1, fsr.lastIndexOf(">"));String nr = getBody(message);System.out.println("\n------------------------------------------");System.out.println("发送人: " + fsr);System.out.println("发送时间:" + message.getSentDate());System.out.println("主题:" + message.getSubject());System.out.println("内容: " + nr);System.out.println("附件名称:" + fileName);System.out.println("大小为:" + bodyPart.getSize());System.out.println("邮件id:" + messageID);InputStream inputStream = null;FileOutputStream fos = null;try {inputStream = bodyPart.getInputStream();String emailFileUrl = "/usr/email/" + format;String emailFilePath = emailFileUrl + File.separator + fileName;//判断邮件存放目录是否存在,不存在则创建File fileDir = new File(emailFileUrl);if (!fileDir.isDirectory()) {fileDir.mkdirs();}//判断当前接收的邮件是否存在,不存在则创建File file = new File(emailFilePath);if (!file.exists()) {file.createNewFile();}//将接收到的邮件附件以流的形式写入创建的文件中fos = new FileOutputStream(emailFilePath);byte[] b = new byte[1024];int length;while ((length = inputStream.read(b)) > 0) {fos.write(b, 0, length);}} catch (Exception e) {e.printStackTrace();} finally {if (inputStream != null) {inputStream.close();}if (fos != null) {fos.close();}}}}}}/**** 获取邮件内容**/	public String getBody(Part part) throws Exception {if (part.isMimeType("text/*")) {return part.getContent().toString();}if (part.isMimeType("multipart/*")) {Multipart multipart = (Multipart) part.getContent();for (int i = 0; i < multipart.getCount(); i++) {BodyPart bodyPart = multipart.getBodyPart(i);String body = getBody(bodyPart);if (!body.isEmpty()) {return body;}}}return "";}}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部