package com.phoenics.mail; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; 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.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; public class ReceiveMail { // 21-30行把本程序所用变量进行定义。 具体在main中对它们赋植。 private MimeMessage mimeMsg; // MIME邮件对象 private Session session; // 邮件会话对象 private Properties props; // 系统属性 private boolean needAuth = false; // smtp是否需要认证 private String username = ""; // smtp认证用户名和密码 private String password = ""; private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成//MimeMessage对象 private MimeMessage mimeMessage = null; private String saveAttachPath = ""; // 附件下载后的存放目录 public ReceiveMail(MimeMessage mimeMessage) { this.mimeMessage = mimeMessage; } public ReceiveMail(String smtp) { setSmtpHost(smtp); createMimeMessage(); } public ReceiveMail() { } public void setSmtpHost(String hostName) { System.out.println("设置系统属性:mail.smtp.host = " + hostName); if (props == null) props = System.getProperties(); // 获得系统属性对象 System.out.println("hostName:"+hostName); props.put("mail.smtp.host", hostName); } public boolean createMimeMessage() { boolean flag = false; try { System.out.println("准备获取邮件会话对象!"); session = Session.getDefaultInstance(props, null); // 获得邮件会话对象 } catch (Exception e) { System.err.println("获取邮件会话对象时发生错误!" + e); flag = false; } System.out.println("准备创建MIME邮件对象!"); try { mimeMsg = new MimeMessage(session); // 创建MIME邮件对象 mp = new MimeMultipart(); // mp 一个multipart对象 flag = true; } catch (Exception e) { System.err.println("创建MIME邮件对象失败!" + e); flag = false; } return flag; } public void setNeedAuth(boolean need) { System.out.println("设置smtp身份认证:mail.smtp.auth = " + need); if (props == null) props = System.getProperties(); if (need) { props.put("mail.smtp.auth", "false"); props.put("mail.smtp.quitwait", "false"); } else { props.put("mail.smtp.auth", "false"); props.put("mail.smtp.quitwait", "false"); } } public void setNamePass(String name, String pass) { System.out.println("程序得到用户名与密码"); username = name; password = pass; } public boolean setSubject(String mailSubject) { System.out.println("设置邮件主题!"); try { mimeMsg.setSubject(mailSubject); return true; } catch (Exception e) { System.err.println("设置邮件主题发生错误!"); return false; } } public boolean setBody(String mailBody) { try { System.out.println("设置邮件体格式"); BodyPart bp = new MimeBodyPart(); bp.setContent( "<meta http-equiv=Content-Type content=text/html; charset=gb2312>" + mailBody, "text/html;charset=GB2312"); mp.addBodyPart(bp); return true; } catch (Exception e) { System.err.println("设置邮件正文时发生错误!" + e); return false; } } public boolean addFileAffix(String filename) { System.out.println("增加邮件附件:" + filename); try { BodyPart bp = new MimeBodyPart(); FileDataSource fileds = new FileDataSource(filename); bp.setDataHandler(new DataHandler(fileds)); bp.setFileName(fileds.getName()); mp.addBodyPart(bp); return true; } catch (Exception e) { System.err.println("增加邮件附件:" + filename + "发生错误!" + e); return false; } } public boolean setFrom(String from) { System.out.println("设置发信人!"); try { mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人 return true; } catch (Exception e) { return false; } } public boolean setTo(String to) { System.out.println("设置收信人"); if (to == null) { return false; } try { mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); return true; } catch (Exception e) { return false; } } public boolean setCopyTo(String copyto) { System.out.println("发送附件到"); if (copyto == null) return false; try { mimeMsg.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress.parse(copyto)); return true; } catch (Exception e) { return false; } } // 发送邮件 public boolean sendout() { try { mimeMsg.setContent(mp); mimeMsg.saveChanges(); System.out.println("正在发送邮件...."); Session mailSession = Session.getInstance(props, null); Transport transport = mailSession.getTransport("smtp"); // transport.connect((String) props.get("mail.smtp.host"), username, password); transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO)); // transport.send(mimeMsg); System.out.println("content.." + mimeMsg.toString()); System.out.println("发送邮件成功!"); transport.close(); return true; } catch (Exception e) { System.err.println("邮件发送失败!" + e); return false; } } public void saveAttachment(Part part) { try { 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("gbk") != -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()); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 获取文件扩展名 * * @param filename * @return */ public static String getExtensionName(String fileName) { String extensionName = ""; if ((fileName != null) && (fileName.length() > 0)) { int dot = fileName.lastIndexOf('.'); if ((dot > -1) && (dot < (fileName.length() - 1))) { extensionName = fileName.substring(dot + 1); // excel文件扩展名有两种常用形式.xls和.xlsx,此两种扩展名统一放在xlsx目录下 if (extensionName.equalsIgnoreCase("pdf")) { extensionName = "pdf"; } return extensionName; } } return extensionName; } /** * 获得附件存放路径 */ public String getAttachPath() { return saveAttachPath; } /** * 真正的保存附件到指定目录里 */ private void saveFile(String fileName, InputStream in) { String osName = System.getProperty("os.name"); String storedir = getAttachPath(); String separator = ""; String extensionName = ""; if (osName == null) osName = ""; if (osName.toLowerCase().indexOf("win") != -1) { separator = "//"; if (storedir == null || storedir.equals("")) { storedir = "D://tmp//"; } } else { separator = "/"; storedir = "/tmp"; } // pdf和excel文件分开放在临时目录下 extensionName = ReceiveMail.getExtensionName(fileName); storedir += extensionName; // fileName = UIDGenerator.getUID(); File storefile = null; try { storefile = new File(MimeUtility.decodeText(storedir) + MimeUtility.decodeText(separator) + MimeUtility.decodeText(fileName)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // 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) { exception.printStackTrace(); // throw new Exception("文件保存失败!"); } finally { try { bos.close(); bis.close(); } catch (IOException e) { e.printStackTrace(); } } } public void sendMail() { String mailbody = "测试 1"; ReceiveMail themail = new ReceiveMail("smtp.163.com"); themail.setNeedAuth(false); if (themail.setSubject("xlsx1") == false) return; // 邮件内容 支持html 如 <font color=red>欢迎光临</font> <a // href=\"http://www.laabc.com\">啦ABC</a> if (themail.setBody(mailbody) == false) return; // 收件人邮箱 if (themail.setTo("[email protected]") == false) return; // 发件人邮箱 if (themail.setFrom("[email protected]") == false) return; // 设置附件 themail.addFileAffix("D:\\1.pdf"); themail.addFileAffix("D:\\2.pdf"); themail.addFileAffix("D:\\3.pdf"); // if (themail.addFileAffix("D:\\crm2.pdf") == false) // return; // 附件在本地机子上的绝对路径 themail.setNamePass("username", "password"); // 用户名与密码 themail.sendout(); } public void getMail() { try { Properties properties = System.getProperties(); properties.put("mail.store.protocol", "imap"); properties.put("mail.imap.host", "imap.163.com"); Session session = Session.getDefaultInstance(properties); Store store = session.getStore("imap"); store.connect("imap.163.com", "username", "password"); Folder folder = store.getDefaultFolder(); folder = folder.getFolder("INBOX"); folder.open(Folder.READ_WRITE); System.out.println("新邮件:" + folder.getUnreadMessageCount()); Message[] message = folder.getMessages(); System.out.println("mail count:" + message.length); for (int i = 0; i < message.length; i++) { if (!message[i].getFlags().contains(Flags.Flag.SEEN)) { message[i].setFlag(Flags.Flag.SEEN, true); ReceiveMail receiveMail = new ReceiveMail((MimeMessage) message[i]); receiveMail.saveAttachment((Part) message[i]); } } System.out.println("接收完毕"); folder.close(false); store.close(); } catch (Exception ex) { System.out.println(ex); } } public static void main(String[] args) { ReceiveMail mail = new ReceiveMail("smtp.163.com"); //mail.sendMail(); mail.getMail(); } }