Receive Email in Java using JavaMail – GMail IMAP Example
来源:互联网 发布:人工智能的原理 编辑:程序博客网 时间:2024/05/16 17:07
Receive Email in Java using JavaMail – GMail IMAP Example
In this tutorial you can learn to write a Java web application to receive emails and display them.
Do you know any free or open source email client other than Thunderbird that does an impressive job. Shall we write one?
Think about writing our own email client and it will be cool.
This tutorial will help you started.
I will write a web client using Java / JSP / HTML / Bootstrap and it will serve as a IMAP client to read emails from IMAP “inbox” folder and display as a list.
Along with that, one complete email will be shown in the UI.
Have a look at the screen shot of the example application and don’t get deceived from that.
The list of emails, one full email is dynamic and other than that is just filler information.
You can use this application and enhance it to make a real good email web client.
Already I have written about sending email using GMail SMTP with JavaMail.
Use that article and combine it with this application, so that you will get both send and receive email functionality.
I have used a responsive Bootstrap theme for this. You can download this complete example application at the end of this tutorial.
Almost all the links are dummy and its just a one page example application and you may enhance it to the next level.
May be sometime in future I will try to make this a full fledged email client.
Receive Email Example Project
This example project has only two files.
One Java file and a JSP page. If you plan to use it in production, you may have to organize and layer it.
The UI can be made better with the use of JSP tag libraries. For simplicity, I have used scriplets.
MailService.java
package com.javapapers.java.mail;import java.util.Properties;import javax.mail.Folder;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Store;import javax.mail.URLName;public class MailService {private Session session;private Store store;private Folder folder;// hardcoding protocol and the folder// it can be parameterized and enhanced as requiredprivate String protocol = "imaps";private String file = "INBOX";public MailService() {}public boolean isLoggedIn() {return store.isConnected();}/** * to login to the mail host server */public void login(String host, String username, String password)throws Exception {URLName url = new URLName(protocol, host, 993, file, username, password);if (session == null) {Properties props = null;try {props = System.getProperties();} catch (SecurityException sex) {props = new Properties();}session = Session.getInstance(props, null);}store = session.getStore(url);store.connect();folder = store.getFolder(url);folder.open(Folder.READ_WRITE);}/** * to logout from the mail host server */public void logout() throws MessagingException {folder.close(false);store.close();store = null;session = null;}public int getMessageCount() {int messageCount = 0;try {messageCount = folder.getMessageCount();} catch (MessagingException me) {me.printStackTrace();}return messageCount;}public Message[] getMessages() throws MessagingException {return folder.getMessages();}}
List the Email Headers in Inbox
I am showing the essential part of the file and you can get the complete file from the download.
You need to put your GMail email and password at the place shown.
Those things should be parameterized and used accordingly in a serious application.
<%// It is good to Use Tag Library to display dynamic content MailService mailService = new MailService();mailService.login("imap.gmail.com", "your gmail email here","your gmail password here");int messageCount = mailService.getMessageCount();//just for tutorial purposeif (messageCount > 5)messageCount = 5;Message[] messages = mailService.getMessages();for (int i = 0; i < messageCount; i++) {String subject = "";if (messages[i].getSubject() != null)subject = messages[i].getSubject();Address[] fromAddress = messages[i].getFrom();%><div class="mail_list"><div class="left"><i class="fa fa-circle"></i> <i class="fa fa-edit"></i></div><div class="right"><h3><%out.print(fromAddress[0].toString());%><small><%=messages[i].getReceivedDate()%></small></h3><p><%=subject%>...</p></div></div><%}%>
Display a Received Email
Following code displays a mail in the screen. You can choose to display the latest email received.
<%if (messageCount > 0) {String subject = "";if (messages[0].getSubject() != null)subject = messages[0].getSubject();Address[] fromAddress = messages[0].getFrom();Address[] replyToAddress = messages[0].getReplyTo();%><div class="inbox-body"><div class="mail_heading row"><div class="col-md-8"><div class="compose-btn"><a class="btn btn-sm btn-primary"href="mail_compose.html"><i class="fa fa-reply"></i>Reply</a><button title="" data-placement="top"data-toggle="tooltip" type="button"data-original-title="Print" class="btn btn-sm tooltips"><i class="fa fa-print"></i></button><button title="" data-placement="top"data-toggle="tooltip" data-original-title="Trash"class="btn btn-sm tooltips"><i class="fa fa-trash-o"></i></button></div></div><div class="col-md-4 text-right"><p class="date"><%=messages[0].getReceivedDate()%></p></div><div class="col-md-12"><h4><%=subject%></h4></div></div><div class="sender-info"><div class="row"><div class="col-md-12"><strong> <% out.print(fromAddress[0].toString()); %></strong> to <strong>me</strong> <a class="sender-dropdown"><iclass="fa fa-chevron-down"></i></a></div></div></div><div class="view-mail"><%Message message = messages[0];Object content = message.getContent();// check for string// then check for multipartif (content instanceof String) {out.println(content);} else if (content instanceof Multipart) {Multipart multiPart = (Multipart) content;int multiPartCount = multiPart.getCount();for (int i = 0; i < multiPartCount; i++) {BodyPart bodyPart = multiPart.getBodyPart(i);Object o;o = bodyPart.getContent();if (o instanceof String) {out.println(o);}}}%><p><%=messages[0].getContent()%></p></div><div class="compose-btn pull-left"><a class="btn btn-sm btn-primary" href="mail_compose.html"><iclass="fa fa-reply"></i> Reply</a><button class="btn btn-sm "><i class="fa fa-arrow-right"></i> Forward</button><button title="" data-placement="top" data-toggle="tooltip"type="button" data-original-title="Print"class="btn btn-sm tooltips"><i class="fa fa-print"></i></button><button title="" data-placement="top" data-toggle="tooltip"data-original-title="Trash" class="btn btn-sm tooltips"><i class="fa fa-trash-o"></i></button></div></div><%}%>
- Receive Email in Java using JavaMail – GMail IMAP Example
- JavaMail API – Sending Email Via Gmail SMTP Example
- connect to Gmail Imap using javamail
- Access GMail with imap using java mail api
- Send Email Using Gmail
- javamail使用IMAP协议收取gmail邮件
- Using Gmail for GoDaddy Email
- 【Android】发送Email(内置Gmail和JavaMail)
- Accessing IMAP email accounts using telnet.
- 利用JavaMail通过POP3协议、IMAP协议收取Gmail邮箱
- javaMail java发送email
- Send Email Using Gmail (Continued) - Testing
- Accessing an IMAP account using SSL (OpenSSL on Gmail)
- javamail+imap
- Guide to Setup Gmail IMAP in Outlook 2010
- Using Spinlock in linux : Example
- javamail gmail
- Example: Showing a Message in JavaMail
- 去除inline-block元素间间距的N种方法
- 二层转发机制&MAC地址表会溢出吗(为啥具有老化时间)
- OpenCV项目实战机器视觉之零件缺陷检测(1)
- HomeBrew 及React-native环境配置
- 第六期 基于模拟器的Helloworld 内核驱动 《手机就是开发板》
- Receive Email in Java using JavaMail – GMail IMAP Example
- Html的语义化(h5改进)
- laravel 生成验证码的方法
- 张量基本知识
- 27.explain
- 韩顺平java笔记03
- 【备忘】JavaEE项目大全视频教程下载
- T-SQL字符串的N‘
- 安装VirtualBox遇到的错误