POM
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>maventest</groupId> <artifactId>maventest</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> </dependencies> </project>
1、main
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; public class Main { public static void main(String[] args) { boolean sslEnable = false; String userName = "ssb@daixinet.com"; String password = "****"; // 发送邮件 String smtpHost = "smtp.mxhichina.com"; String smtpPort = "25"; String mailSubject = "test mail" + new Date().toString(); String mailBody = "test mail"; List<String> toAddress = new ArrayList<String>(); toAddress.add("zyl@daixinet.com"); List<EmailAttachment> attachmentList = new ArrayList<EmailAttachment>(); EmailAttachment emailAttachment = new EmailAttachment(); attachmentList.add(emailAttachment); emailAttachment.setFileName("01.txt"); File file = new File("D:\\01.txt"); try { InputStream inputStream = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(1000); byte[] b = new byte[1000]; int n; while ((n = inputStream.read(b)) != -1) { bos.write(b, 0, n); } inputStream.close(); bos.close(); emailAttachment.setAttachment(bos.toByteArray()); } catch (Exception e) { System.out.println(e.getMessage()); } // 接收邮件 String pop3Host = "pop3.mxhichina.com"; String pop3Port = "110"; IReceiveHandle receiveHandle = new MyReceiveHandle(); MailUtil mailUtil = new MailUtil(); mailUtil.setSslEnable(sslEnable); mailUtil.setUserName(userName); mailUtil.setPassword(password); mailUtil.setSmtpHost(smtpHost); mailUtil.setSmtpPort(smtpPort); mailUtil.setMailSubject(mailSubject); mailUtil.setMailBody(mailBody); mailUtil.setToAddress(toAddress); mailUtil.setAttachmentList(attachmentList); mailUtil.setPop3Host(pop3Host); mailUtil.setPop3Port(pop3Port); mailUtil.setiReceiveHandle(receiveHandle); try { //mailUtil.Send(); } catch (Exception e) { System.out.println(e.getMessage()); } try { mailUtil.Receive(); } catch (Exception e) { e.printStackTrace(); } System.out.println("End"); } }
2、MailUtil
import com.sun.mail.pop3.POP3Folder; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.io.*; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; public class MailUtil { private boolean sslEnable; private String userName; private String password; // 发送邮件 private String smtpHost; private String smtpPort = "25"; private String mailSubject; private String mailBody; private List<String> toAddress = new ArrayList<String>(); private List<EmailAttachment> attachmentList = new ArrayList<EmailAttachment>(); // 接收邮件 private String pop3Host; private String pop3Port = "110"; private IReceiveHandle iReceiveHandle; public boolean isSslEnable() { return sslEnable; } public void setSslEnable(boolean sslEnable) { this.sslEnable = sslEnable; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSmtpHost() { return smtpHost; } public void setSmtpHost(String smtpHost) { this.smtpHost = smtpHost; } public String getSmtpPort() { return smtpPort; } public void setSmtpPort(String smtpPort) { this.smtpPort = smtpPort; } public String getMailSubject() { return mailSubject; } public void setMailSubject(String mailSubject) { this.mailSubject = mailSubject; } public String getMailBody() { return mailBody; } public void setMailBody(String mailBody) { this.mailBody = mailBody; } public List<String> getToAddress() { return toAddress; } public void setToAddress(List<String> toAddress) { this.toAddress = toAddress; } public List<EmailAttachment> getAttachmentList() { return attachmentList; } public void setAttachmentList(List<EmailAttachment> attachmentList) { this.attachmentList = attachmentList; } public String getPop3Host() { return pop3Host; } public void setPop3Host(String pop3Host) { this.pop3Host = pop3Host; } public String getPop3Port() { return pop3Port; } public void setPop3Port(String pop3Port) { this.pop3Port = pop3Port; } public IReceiveHandle getiReceiveHandle() { return iReceiveHandle; } public void setiReceiveHandle(IReceiveHandle iReceiveHandle) { this.iReceiveHandle = iReceiveHandle; } // 公共方法 public void Send() throws Exception { try { // 属性封装 Properties props = System.getProperties(); props.put("mail.pop3.ssl.enable", sslEnable); props.put("mail.smtp.host", smtpHost); props.put("mail.stmp.port", smtpPort); props.put("mail.smtp.auth", "true"); // 验证 MailAuthenticator authenticator = new MailAuthenticator(userName, password); Session session = Session.getDefaultInstance(props, authenticator); // 信息 Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(userName)); if (toAddress.size() < 1) { throw new Exception("发送地址为空"); } InternetAddress[] address = new InternetAddress[toAddress.size()]; for (int idx = 0; idx < toAddress.size(); idx++) { address[idx] = new InternetAddress(toAddress.get(idx)); } msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(mailSubject); // 邮件内容 Multipart multipart = new MimeMultipart(); msg.setContent(multipart); // 邮件正文 BodyPart bodyPart = new MimeBodyPart(); multipart.addBodyPart(bodyPart); bodyPart.setText(mailBody); // 邮件附件 List<File> files = new ArrayList<File>(); if (attachmentList.size() > 0) { for (EmailAttachment emailAttachment : attachmentList) { bodyPart = new MimeBodyPart(); multipart.addBodyPart(bodyPart); bodyPart.setFileName(emailAttachment.getFileName()); // 创建文件 File file = new File(emailAttachment.getFileName()); files.add(file); if (file.exists()) { file.delete(); } file.createNewFile(); OutputStream outputStream = new FileOutputStream(file); outputStream.write(emailAttachment.getAttachment()); outputStream.close(); DataSource source = new FileDataSource(file); bodyPart.setDataHandler(new DataHandler(source)); } } // 发送邮件 Transport.send(msg); // 删除附件 for (File file : files) { if (file.exists()) { file.delete(); } } } catch (Exception ex) { throw ex; } } public void Receive() throws Exception { Store store = null; Folder folder = null; try { // 属性封装 Properties props = System.getProperties(); props.put("mail.pop3.ssl.enable", sslEnable); props.put("mail.pop3.host", pop3Host); props.put("mail.pop3.port", pop3Port); // 验证 Session session = Session.getDefaultInstance(props); store = session.getStore("pop3"); store.connect(userName, password); folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); int size = folder.getMessageCount(); Message messages[] = folder.getMessages(); for (int idx = 0; idx < size; idx++) { if (iReceiveHandle == null) { break; } // 1、UID MimeMessage message = (MimeMessage) folder.getMessage(idx + 1); POP3Folder inbox = (POP3Folder) folder; String uid = inbox.getUID(message); // 根据UID判断是否需要接收 boolean isNeedReceive = iReceiveHandle.isNeedReceive(uid); if (!isNeedReceive) { continue; } // 2、ReceiveEmail 对象 ReceiveEmail receiveEmail = new ReceiveEmail(); Date sentDate = message.getSentDate(); String from = message.getFrom()[0].toString(); String subject = message.getSubject(); String content = getMailContent(messages[idx]); receiveEmail.setSentDate(sentDate); receiveEmail.setFrom(from); receiveEmail.setSubject(subject); // TODO:邮件内容、附件 receiveEmail.setContent(content); boolean isContainAttach = isContainAttach(messages[idx]); if (isContainAttach) { //saveAttachMent(messages[idx]); } // 传递参数 iReceiveHandle.handle(receiveEmail); } } catch (Exception ex) { throw ex; } finally { try { if (folder != null) { folder.close(false); } if (store != null) { store.close(); } } catch (MessagingException e) { e.printStackTrace(); } } } private String getMailContent(Part part) throws Exception { StringBuffer rtn = new StringBuffer(); String contenttype = part.getContentType(); int nameindex = contenttype.indexOf("name"); boolean conname = false; if (nameindex != -1) conname = true; //System.out.println("CONTENTTYPE: " + contenttype); if (part.isMimeType("text/plain") && !conname) { rtn.append((String) part.getContent()); } else if (part.isMimeType("text/html") && !conname) { rtn.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++) { getMailContent(multipart.getBodyPart(i)); } } else if (part.isMimeType("message/rfc822")) { getMailContent((Part) part.getContent()); } else { } return rtn.toString(); } private boolean isContainAttach(Part part) throws Exception { boolean attachflag = false; String contentType = part.getContentType(); if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart mpart = mp.getBodyPart(i); String disposition = mpart.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition .equals(Part.INLINE)))) attachflag = true; else if (mpart.isMimeType("multipart/*")) { attachflag = isContainAttach((Part) mpart); } else { String contype = mpart.getContentType(); if (contype.toLowerCase().indexOf("application") != -1) attachflag = true; if (contype.toLowerCase().indexOf("name") != -1) attachflag = true; } } } else if (part.isMimeType("message/rfc822")) { attachflag = isContainAttach((Part) part.getContent()); } return attachflag; } private void saveAttachMent(Part part) throws Exception { String fileName = ""; if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart mpart = mp.getBodyPart(i); String disposition = mpart.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition .equals(Part.INLINE)))) { fileName = mpart.getFileName(); if (fileName.toLowerCase().indexOf("gb2312") != -1) { fileName = MimeUtility.decodeText(fileName); } saveFile(fileName, mpart.getInputStream()); } else if (mpart.isMimeType("multipart/*")) { saveAttachMent(mpart); } else { fileName = mpart.getFileName(); if ((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)) { fileName = MimeUtility.decodeText(fileName); saveFile(fileName, mpart.getInputStream()); } } } } else if (part.isMimeType("message/rfc822")) { saveAttachMent((Part) part.getContent()); } } private void saveFile(String fileName, InputStream in) throws Exception { String osName = System.getProperty("os.name"); String storedir = ""; String separator = ""; if (osName == null) osName = ""; if (osName.toLowerCase().indexOf("win") != -1) { separator = "\\"; if (storedir == null || storedir.equals("")) storedir = "c:\\tmp"; } else { separator = "/"; storedir = "/tmp"; } File storefile = new File(storedir + separator + fileName); System.out.println("storefile's path: " + storefile.toString()); // for(int i=0;storefile.exists();i++){ // storefile = new File(storedir+separator+fileName+i); // } BufferedOutputStream bos = null; BufferedInputStream bis = null; try { bos = new BufferedOutputStream(new FileOutputStream(storefile)); bis = new BufferedInputStream(in); int c; while ((c = bis.read()) != -1) { bos.write(c); bos.flush(); } } catch (Exception exception) { throw new Exception("文件保存失败!"); } finally { bos.close(); bis.close(); } } }
3、MailAuthenticator
import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class MailAuthenticator extends Authenticator { private String username; private String password; public MailAuthenticator(String username, String password) { this.username = username; this.password = password; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
4、IReceiveHandle
public interface IReceiveHandle { boolean isNeedReceive(String uid); void handle(ReceiveEmail receiveEmail); }
5、EmailAttachment
public class EmailAttachment { private String fileName; private byte[] attachment; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public byte[] getAttachment() { return attachment; } public void setAttachment(byte[] attachment) { this.attachment = attachment; } }
6、MyReceiveHandle
public class MyReceiveHandle implements IReceiveHandle { public boolean isNeedReceive(String uid) { return true; } public void handle(ReceiveEmail receiveEmail) { System.out.println("Start ==================================="); System.out.println(receiveEmail.getFrom()); System.out.println(receiveEmail.getSubject()); System.out.println(receiveEmail.getContent()); System.out.println("End ==================================="); } }
7、ReceiveEmail
import java.util.ArrayList; import java.util.Date; import java.util.List; public class ReceiveEmail { private String uid; private Date sentDate; private String from; private String subject; private String content; private List<byte[]> attachments = new ArrayList<byte[]>(); public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public Date getSentDate() { return sentDate; } public void setSentDate(Date sentDate) { this.sentDate = sentDate; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public List<byte[]> getAttachments() { return attachments; } public void setAttachments(List<byte[]> attachments) { this.attachments = attachments; } }