MailInfo类:
//发送邮件的信息类 public class MailInfo { private String personal;// 姓名 private String subject;// 主题 private Date sentDate = new Date();// 发送时间 private List<String> toList = new ArrayList<String>();// 主送人集合 private List<String> ccList = new ArrayList<String>();// 抄送人集合 private List<String> bccList = new ArrayList<String>();// 密送人集合 private List<String> fileList = new ArrayList<String>();// 附件集合 private List<HtmlImage> imgList = new ArrayList<HtmlImage>();// 发送html所要用到的img图片集合 }
MailClient类:
package org.forever.javamail; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; 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.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.URLName; 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; import javax.mail.util.ByteArrayDataSource; public class MailClient { private static final String CONTENT_ID = "Content-ID"; private static final String TEXT_PLAIN = "text/plain"; private static final String APPLICATION_OCTET_STREAM = "application/octet-stream"; private static final String DEBUG = "debug"; private static final String FALSE = "false"; private static final String TRUE = "true"; private static final String POINT = "."; private static final String INBOX = "INBOX"; private static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; private static final String POP3 = "pop3"; private static final String MAIL = "mail"; private static final String SMTP = "smtp"; private static final String AUTH = "auth"; private static final String HOST = "host"; private int pop3Port = 110; private String pop3Host; private String from;// 发件人邮件地址 private String userName;// 用户名 private String password;// 密码 private Session session;// 会话接口 private String savePath = "C:\\temp\\";// 附件保持路径 public static final int TEXT = 1;// 文本内容 public static final int HTML = 2;// html内容 private String smtpHost;// 域名 public MailClient(String userName, String password, String smtpHost, String pop3Host) { this.smtpHost = smtpHost; this.userName = userName; this.password = password; this.pop3Host = pop3Host; from = userName + "@" + smtpHost; Properties props = System.getProperties(); props.put(MAIL + POINT + SMTP + POINT + HOST, smtpHost); props.put(MAIL + POINT + SMTP + POINT + AUTH, TRUE); props.put(MAIL + POINT + DEBUG, FALSE); session = Session.getDefaultInstance(props, new EmailAuthenticator( userName, password)); } // 发送消息 public void sendMail(MailInfo mailInfo, int sendType) throws Exception { Message message = new MimeMessage(session); Address fromAddress = new InternetAddress(from, mailInfo.getPersonal()); message.setSubject(mailInfo.getSubject()); message.setSentDate(mailInfo.getSentDate()); message.setFrom(fromAddress); Multipart multipart = new MimeMultipart(); switch (sendType) { case TEXT: BodyPart textPart = new MimeBodyPart(); textPart.setContent(mailInfo.getContent(), "text/plain;charset=utf-8"); multipart.addBodyPart(textPart); break; case HTML: BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(mailInfo.getContent(), "text/html;charset=utf-8"); multipart.addBodyPart(htmlPart); break; default: break; } for (String filePath : mailInfo.getFileList()) { File file = new File(filePath); if (!file.exists())continue; BodyPart attchPart = new MimeBodyPart(); DataSource source = new FileDataSource(file); attchPart.setDataHandler(new DataHandler(source)); attchPart.setFileName(MimeUtility.encodeText(file.getName())); multipart.addBodyPart(attchPart); } for (HtmlImage htmlImage : mailInfo.getImgList()) { String filePath = htmlImage.getFilePath(); File file = new File(filePath); if (!file.exists())continue; BodyPart imgPart = new MimeBodyPart(); imgPart.setDataHandler(new DataHandler( new ByteArrayDataSource(ImageUtil.imageToByteArray(filePath),APPLICATION_OCTET_STREAM) )); imgPart.setFileName(MimeUtility.encodeText(file.getName())); imgPart.setHeader(CONTENT_ID, "<"+htmlImage.getCid()+">"); multipart.addBodyPart(imgPart); } message.setContent(multipart); for (String bcc : mailInfo.getBccList()) { message.setRecipient(Message.RecipientType.BCC, new InternetAddress(bcc)); Transport.send(message); } System.out.println("send success....."); } public boolean isRead(Message message) throws Exception { boolean isRead = false; for (Flags.Flag flag : message.getFlags().getSystemFlags()) { if (flag == Flags.Flag.SEEN) { isRead = true; System.out.println("isRead=true......"); } } return isRead; } // 获取消息 public Message[] getMail() throws Exception { URLName urln = new URLName(POP3, pop3Host, pop3Port, null, userName, password); Store store = session.getStore(urln); store.connect(); Folder folder = store.getFolder(INBOX); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages(); return message; } // 清除所有邮件 public void clearAllMail() throws Exception { URLName urln = new URLName(POP3, pop3Host, pop3Port, null, userName, password); Store store = session.getStore(urln); store.connect(); Folder folder = store.getFolder(INBOX); folder.open(Folder.READ_WRITE); Message message[] = folder.getMessages(); for (Message item : message) { System.out.println("MegID: " + item.getMessageNumber() + " Title: " + item.getSubject() + "Flags: " + item.getFlags()); item.setFlag(Flags.Flag.DELETED, true); } folder.close(true); store.close(); } // 打印消息内容 public void printMessage(Message[] message) throws MessagingException, Exception, IOException { SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS); for (Message msg : message) { InternetAddress address = (InternetAddress) msg.getFrom()[0]; System.out.println("messageNumber:" + msg.getMessageNumber()); System.out.println("personal:" + address.getPersonal()); System.out.println("address:" + address.getAddress()); System.out.println("sentDate:" + sdf.format(msg.getSentDate())); System.out.println("status:" + isRead(msg)); System.out.println("subject:" + msg.getSubject()); Object content = msg.getContent(); if (content instanceof Multipart) { Multipart multipart = (Multipart) content; int count = multipart.getCount(); for (int i = 0; i < count; i++) { BodyPart bodyPart = multipart.getBodyPart(i); Object bodyContent = bodyPart.getContent(); String[] mimeType = bodyPart.getContentType().split(";"); System.out.println("type:" + bodyPart.getContentType()); if (APPLICATION_OCTET_STREAM.equals(mimeType[0])) { MimeBodyPart attchPart = (MimeBodyPart) bodyPart; String fileName = MimeUtility.decodeText(attchPart.getFileName()); System.out.println("fileName:" + fileName); InputStream in = attchPart.getInputStream(); FileUtil.saveFile(in, savePath,fileName); } else if (TEXT_PLAIN.equals(mimeType[0])) { System.out.println("content:" + bodyContent); } System.out.println("--------------------------------"); } } else { System.out.println(content); } System.out .println("*************************************************"); } } public String getSavePath() { return savePath; } public void setSavePath(String savePath) { this.savePath = savePath; } public int getPop3Port() { return pop3Port; } public void setPop3Port(int pop3Port) { this.pop3Port = pop3Port; } public String getPop3Host() { return pop3Host; } public void setPop3Host(String pop3Host) { this.pop3Host = pop3Host; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } 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; } }
MailTest测试类:
package org.forever.javamail; import java.io.BufferedReader; import java.io.InputStreamReader; import org.junit.Test; public class MailTest { // 测试用户如下:chenjun,mqq,hds,yw // 测试局域网的发送情况 @Test public void testSendEmail_localhost() { // 假设发送人chenjun,主送人:mqq,抄送人:hds,密送人:yw MailClient cjClient = new MailClient("chenjun", "cj", "localhost", "localhost"); MailInfo cjMail = new MailInfo(); cjMail.setPersonal("陈均"); cjMail.setSubject("吃饭了"); cjMail.setContent("晚上9点,准时开饭"); cjMail.getToList().add("mqq@localhost"); cjMail.getCcList().add("hds@localhost"); cjMail.getBccList().add("yw@localhost"); try { cjClient.sendMail(cjMail, MailClient.TEXT); } catch (Exception e) { e.printStackTrace(); } } // 测试局域网所发邮件的信息是否已经收到 @Test public void testGetEmail_localhost() { MailClient mqqClient = new MailClient("mqq", "mqq", "localhost", "localhost"); MailClient hdsClient = new MailClient("hds", "hds", "localhost", "localhost"); MailClient ywClient = new MailClient("yw", "yw", "localhost", "localhost"); try { mqqClient.printMessage(mqqClient.getMail()); hdsClient.printMessage(hdsClient.getMail()); ywClient.printMessage(ywClient.getMail()); } catch (Exception e) { e.printStackTrace(); } } // 测试向abstractforever外网发送邮件 @Test public void testSendEmail_abstractforever() { // 假设发送人chenjun,主送人:mqq,抄送人:hds,//密送人:yw MailClient cjClient = new MailClient("chenjun", "cj", "abstractforever.gicp.net", "abstractforever.gicp.net"); MailInfo cjMail = new MailInfo(); cjMail.setPersonal("陈均"); cjMail.setSubject("吃饭了"); cjMail.setContent("晚上9点,准时开饭"); cjMail.getToList().add("[email protected]"); cjMail.getCcList().add("[email protected]"); cjMail.getBccList().add("[email protected]"); try { cjClient.sendMail(cjMail, MailClient.TEXT); } catch (Exception e) { e.printStackTrace(); } } // 测试所发邮件的信息是否已经收到 @Test public void testGetEmail_abstractforever() { MailClient mqqClient = new MailClient("mqq", "mqq", "abstractforever.gicp.net", "abstractforever.gicp.net"); MailClient hdsClient = new MailClient("hds", "hds", "abstractforever.gicp.net", "abstractforever.gicp.net"); MailClient ywClient = new MailClient("yw", "yw", "abstractforever.gicp.net", "abstractforever.gicp.net"); MailClient cjClient = new MailClient("chenjun", "cj", "abstractforever.gicp.net", "abstractforever.gicp.net"); try { mqqClient.printMessage(mqqClient.getMail()); hdsClient.printMessage(hdsClient.getMail()); ywClient.printMessage(ywClient.getMail()); cjClient.printMessage(cjClient.getMail()); } catch (Exception e) { e.printStackTrace(); } } // 测试清除邮件服务器的邮件 @Test public void testClearAllEmail_abstractforever() { MailClient mqqClient = new MailClient("mqq", "mqq", "abstractforever.gicp.net", "abstractforever.gicp.net"); MailClient hdsClient = new MailClient("hds", "hds", "abstractforever.gicp.net", "abstractforever.gicp.net"); MailClient ywClient = new MailClient("yw", "yw", "abstractforever.gicp.net", "abstractforever.gicp.net"); MailClient cjClient = new MailClient("chenjun", "cj", "abstractforever.gicp.net", "abstractforever.gicp.net"); try { mqqClient.clearAllMail(); hdsClient.clearAllMail(); ywClient.clearAllMail(); cjClient.clearAllMail(); } catch (Exception e) { e.printStackTrace(); } } // 测试向163外网发送邮件 @Test public void testSendEmail_163() { // 假设发送人chenjun,主送人:abstractforever,抄送人:abstractforever,密送人:abstractforever MailClient cjClient = new MailClient("chenjun", "cj", "abstractforever.gicp.net", "abstractforever.gicp.net"); MailInfo cjMail = new MailInfo(); cjMail.setPersonal("陈均"); cjMail.setSubject("吃饭了"); cjMail.setContent("晚上9点,准时开饭"); cjMail.getToList().add("[email protected]"); cjMail.getCcList().add("[email protected]"); cjMail.getBccList().add("[email protected]"); cjMail.getFileList().add("e:\\a.doc"); cjMail.getFileList().add("e:\\中文附件.doc"); try { cjClient.sendMail(cjMail, MailClient.TEXT); } catch (Exception e) { e.printStackTrace(); } } // 测试获取163邮件信息 @Test public void testGetEmail_163() { MailClient afClient = new MailClient("abstractforever", "*****", "smtp.163.com", "pop3.163.com"); try { afClient.printMessage(afClient.getMail()); } catch (Exception e) { e.printStackTrace(); } } // 测试清除163邮件信息 @Test public void testClearAllEmail_163() { MailClient cjClient = new MailClient("abstractforever", "*****", "smtp.163.com", "pop3.163.com"); try { cjClient.clearAllMail(); } catch (Exception e) { e.printStackTrace(); } } // 测试向qq外网发送邮件 @Test public void testSendEmail_qq() { // 假设发送人chenjun,主送人:396481925,抄送人:396481925,密送人:396481925 MailClient cjClient = new MailClient("chenjun", "cj", "abstractforever.gicp.net", "abstractforever.gicp.net"); MailInfo cjMail = new MailInfo(); cjMail.setPersonal("陈均"); cjMail.setSubject("吃饭了"); cjMail.setContent("晚上9点,准时开饭"); cjMail.getToList().add("[email protected]"); cjMail.getCcList().add("[email protected]"); cjMail.getBccList().add("[email protected]"); try { cjClient.sendMail(cjMail, MailClient.TEXT); } catch (Exception e) { e.printStackTrace(); } } // 测试获取qq邮件信息 @Test public void testGetEmail_qq() { MailClient qqClient = new MailClient("396481925", "*****", "smtp.qq.com", "pop.qq.com"); try { qqClient.printMessage(qqClient.getMail()); } catch (Exception e) { e.printStackTrace(); } } // 测试清除qq邮件信息 @Test public void testClearAllEmail_qq() { MailClient cjClient = new MailClient("396481925", "*****", "smtp.qq.com", "pop.qq.com"); try { cjClient.clearAllMail(); } catch (Exception e) { e.printStackTrace(); } } // 测试向abstractforever外网发送邮件,带附件的 @Test public void testSendEmailAtt_abstractforever() { // 假设发送人chenjun,主送人:mqq,抄送人:hds,//密送人:yw MailClient cjClient = new MailClient("chenjun", "cj", "abstractforever.gicp.net", "abstractforever.gicp.net"); MailInfo cjMail = new MailInfo(); cjMail.setPersonal("陈均"); cjMail.setSubject("吃饭了"); cjMail.setContent("晚上9点,准时开饭"); cjMail.getToList().add("[email protected]"); cjMail.getFileList().add("e:\\a.doc"); cjMail.getFileList().add("e:\\中文附件.doc"); try { cjClient.sendMail(cjMail, MailClient.TEXT); } catch (Exception e) { e.printStackTrace(); } } // 测试向abstractforever外网获取邮件,带附件的 @Test public void testGetEmailAtt_abstractforever() { MailClient mqqClient = new MailClient("mqq", "mqq", "abstractforever.gicp.net", "abstractforever.gicp.net"); try { mqqClient.printMessage(mqqClient.getMail()); } catch (Exception e) { e.printStackTrace(); } } // 测试发送html内容,带图片 @Test public void testSendEmailHtml_163() { // 假设发送人chenjun,主送人:abstractforever,抄送人:abstractforever,密送人:abstractforever MailClient cjClient = new MailClient("chenjun", "cj", "abstractforever.gicp.net", "abstractforever.gicp.net"); MailInfo cjMail = new MailInfo(); cjMail.setPersonal("陈均"); cjMail.setSubject("吃饭了"); StringBuffer html = new StringBuffer(); String line = ""; try { BufferedReader in = new BufferedReader(new InputStreamReader( MailTest.class.getClassLoader().getResourceAsStream( "table.html"), "UTF-8")); while ((line = in.readLine()) != null) { html.append(line); } } catch (Exception e1) { e1.printStackTrace(); } System.out.println(html); cjMail.setContent(html.toString()); cjMail.getImgList().add(new HtmlImage("img_1", "e:\\a.jpg")); cjMail.getToList().add("[email protected]"); cjMail.getFileList().add("e:\\a.doc"); cjMail.getFileList().add("e:\\中文附件.doc"); try { cjClient.sendMail(cjMail, MailClient.HTML); } catch (Exception e) { e.printStackTrace(); } } }