Java 傳送郵件工具類
阿新 • • 發佈:2019-01-11
package com.test.common.util.mail; import java.util.ArrayList; import java.util.Date; import java.util.List; public class MailInfo { private String from; private String to; private String cc; private String bcc; private String subject; private String content; private String sendServer; private String sendUser; private String sendPass; private boolean needAuth = false; private String protocol; private Long port; private List<String> attachFiles; private Date sendDate; private List<String> attachFileNames; private String mailFileName; public MailInfo(){ this.attachFiles = new ArrayList<String>(); this.attachFileNames = new ArrayList<String>(); } public String getMailInfo(){ return(" from: " + this.getFrom() + "\n" + " to: " + this.getTo() + "\n" + " cc: " + this.getCc() + "\n" + " bcc: " + this.getBcc() + "\n" + "Subject: " + this.getSubject() + "\n" + "Content: " + "\n" + this.getContent() ); } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getCc() { return cc; } public void setCc(String cc) { this.cc = cc; } public String getBcc() { return bcc; } public void setBcc(String bcc) { this.bcc = bcc; } 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 String getSendServer() { return sendServer; } public void setSendServer(String sendServer) { this.sendServer = sendServer; } public String getSendUser() { return sendUser; } public void setSendUser(String sendUser) { this.sendUser = sendUser; } public String getSendPass() { return sendPass; } public void setSendPass(String sendPass) { this.sendPass = sendPass; } public boolean isNeedAuth() { return needAuth; } public void setNeedAuth(boolean needAuth) { this.needAuth = needAuth; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public Long getPort() { return port; } public void setPort(Long port) { this.port = port; } public List<String> getAttachFiles() { return attachFiles; } public void setAttachFiles(List<String> attachFiles) { this.attachFiles = attachFiles; } public Date getSendDate() { return sendDate; } public void setSendDate(Date sendDate) { this.sendDate = sendDate; } public List<String> getAttachFileNames() { return attachFileNames; } public void setAttachFileNames(List<String> attachFileNames) { this.attachFileNames = attachFileNames; } public String getMailFileName() { return mailFileName; } public void setMailFileName(String mailFileName) { this.mailFileName = mailFileName; } } package com.test.common.util.mail; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.BodyPart; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.PasswordAuthentication; 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 com.test.common.util.file.FileUtils; /** * * 類描述 :用於Email傳送、接收的工具類。 * */ public class MailUtils { public final static String PROTOCOL_SMTP = "smtp"; public final static String PROTOCOL_POP3 = "pop3"; public final static String PROTOCOL_IMAP = "imap"; public final static String ERROR_NOMAILTO = "沒有指定收件人"; public final static String ERROR_NOSUBJECT = "沒有指定郵件主題"; public final static String ERROR_NOMAILSERVER = "沒有指定郵件伺服器"; public final static String ERROR_NOUSER = "沒有指定登入郵箱的使用者"; private static Authenticator getAuthenticator(String user,String pass){ class SmtpAuth extends Authenticator { private String username,password; public SmtpAuth(String username,String password){ this.username = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username,password); } } return(new SmtpAuth(user, pass)); } /** * 傳送郵件 * * @param toEmailBox * 收件人郵箱 * @param subject * 郵件主題 * @param content * 郵件內容 * @param attachs * 附件列表 * @return void * @throws Exception */ public static void sendEmail(MailInfo mailInfo) throws Exception { if(mailInfo.getTo() == null || mailInfo.getTo().trim().equals("")){ throw new Exception(ERROR_NOMAILTO); } if(mailInfo.getSubject() == null || mailInfo.getSubject().equals("")){ throw new Exception(ERROR_NOSUBJECT); } if(!MailUtils.PROTOCOL_SMTP.equalsIgnoreCase(mailInfo.getProtocol()) || !MailUtils.PROTOCOL_IMAP.equalsIgnoreCase(mailInfo.getProtocol())){ mailInfo.setProtocol(MailUtils.PROTOCOL_SMTP); } Properties props = System.getProperties(); props.put("mail.smtp.host", mailInfo.getSendServer()); props.put("mail.smtp.auth", mailInfo.isNeedAuth()?"true":"false"); Authenticator smtpAuth = getAuthenticator(mailInfo.getSendUser(), mailInfo.getSendPass()); Session session = Session.getInstance(props, smtpAuth); MimeMessage mimeMsg = new MimeMessage(session); MimeMultipart multipart = new MimeMultipart(); mimeMsg.setSubject(mailInfo.getSubject()); BodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent("" + mailInfo.getContent(), "text/html;charset=GB2312"); multipart.addBodyPart(bodyPart); if(mailInfo.getAttachFiles() != null){ for(String f:mailInfo.getAttachFiles()){ File file = new File(f); if(!file.exists()){ throw new Exception("附件【" + f + "】不存在."); } MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(file); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(fds.getName()); multipart.addBodyPart(mbp); } } mimeMsg.addFrom(InternetAddress.parse(mailInfo.getFrom())); mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse (mailInfo.getTo())); if(mailInfo.getCc()!=null && !mailInfo.getCc().trim().equals("")){ mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(mailInfo.getCc())); } if(mailInfo.getBcc()!=null && !mailInfo.getBcc().trim().equals("")){ mimeMsg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(mailInfo.getBcc())); } mimeMsg.setSentDate(new Date()); mimeMsg.setContent(multipart); mimeMsg.saveChanges(); //session.setDebug(true); // 是否在控制檯顯 示debug資訊 Transport transport = session.getTransport(mailInfo.getProtocol()); transport.connect(mailInfo.getSendServer(),mailInfo.getSendUser(), mailInfo.getSendPass()); transport.sendMessage(mimeMsg, mimeMsg.getRecipients (Message.RecipientType.TO)); transport.close(); } /** * 解析郵件,把得到的郵件內容儲存到一個StringBuffer物件中: 解析郵件:主要是根據 MimeType型別的不同執行不同的操作,一步一步的解析 * * @param part * @throws Exception */ private static String getMailContent(Part part) throws Exception { String result = ""; String contenttype; contenttype = part.getContentType(); int nameindex = contenttype.indexOf("name"); boolean conname = false; if (nameindex != -1) { conname = true; } if (part.isMimeType("text/plain") && !conname) { result = result + (String) part.getContent(); } else if (part.isMimeType("multipart/*")) { Multipart multipart = (Multipart) part.getContent(); int counts = multipart.getCount(); for (int i = 0; i < counts; i++) { result = result + getMailContent(multipart.getBodyPart (i)); } } else if (part.isMimeType("message/rfc822")) { result = result + getMailContent((Part) part.getContent()); } return(result); } private static String getAddress(Address[] addrs){ String result = ""; if(addrs == null || addrs.length == 0){ return result; } for(Address addr: addrs){ InternetAddress iaddr = (InternetAddress)addr; String m = iaddr.getAddress(); result = result + ',' + m; } if(!"".equals(result)){ result = result.substring(1); } return result; } /** * 儲存檔案到指定目錄裡 * * @param fileName * @param in * @param path * @throws Exception */ private static void saveFile(String fileName, InputStream in) throws Exception { OutputStream os = new FileOutputStream(fileName,true); try { byte[] buf = new byte[4096]; while(true){ int cnt = in.read(buf); if(cnt > -1){ os.write(buf, 0, cnt); } if(cnt < buf.length){ break; } } } finally { os.flush(); os.close(); } } /** * 儲存附件 * * @param part * @throws Exception */ private static void extractAttachMent(Part part,List<String> fileNames,List<String> files,String tempPath) 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(); fileName = new String(mpart.getFileName ().getBytes("ISO-8859-1"), "utf-8"); //if (fileName.toLowerCase().indexOf("utf-8") != -1) { fileName = MimeUtility.decodeText (fileName); //} fileNames.add(fileName); String tfile = FileUtils.getTempFile(tempPath, "mail", fileName.substring(fileName.lastIndexOf("."))); files.add(tfile); saveFile(tfile, mpart.getInputStream()); } else if (mpart.isMimeType("multipart/*")) { extractAttachMent(mpart,fileNames,files,tempPath); } else { fileName = mpart.getFileName(); if(fileName != null){ //if (fileName.toLowerCase().indexOf("utf -8") != -1) { fileName = MimeUtility.decodeText (fileName); //} fileNames.add(fileName); String tfile = FileUtils.getTempFile (tempPath, "mail", fileName.substring(fileName.lastIndexOf("."))); files.add(tfile); saveFile(tfile, mpart.getInputStream()); } } } } else if (part.isMimeType("message/rfc822")) { extractAttachMent((Part) part.getContent (),fileNames,files,tempPath); } } public static List<MailInfo> receiveMails(String mailServer,Long serverPort,String protocol,String user,String pass,String tempPath,boolean isdelete) throws Exception{ //引數檢查 if(mailServer == null || "".equals(mailServer.trim())){ throw new Exception(ERROR_NOMAILSERVER); } if(serverPort == null || serverPort.intValue() <= 0){ serverPort = new Long(110); } if(protocol == null || "".equals(protocol.trim())){ protocol = "pop3"; } if(user == null || "".equals(user.trim())){ throw new Exception(ERROR_NOUSER); } if(tempPath == null || "".equals(tempPath.trim())){ tempPath = System.getProperty("java.io.tmpdir"); } File f = new File(tempPath); f.mkdirs(); //準備收郵件 List<MailInfo> mails = new ArrayList<MailInfo>(); Properties props = System.getProperties(); props.put("mail.smtp.host", mailServer); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, null); URLName urln = new URLName(protocol, mailServer, serverPort.intValue(), null,user, pass); //接收郵件並進行處理 Store store = session.getStore(urln); try{ store.connect(); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); Message[] messages = folder.getMessages(); if (messages != null){ for(int i = 0; i < messages.length; i++){ Message msg =messages[i]; MailInfo mailInfo = new MailInfo(); mailInfo.setContent(getMailContent((Part)msg)); mailInfo.setSubject(MimeUtility.decodeText(msg.getSubject ())); mailInfo.setFrom(getAddress(msg.getFrom())); mailInfo.setTo(getAddress(msg.getRecipients (Message.RecipientType.TO))); mailInfo.setCc(getAddress(msg.getRecipients (Message.RecipientType.CC))); mailInfo.setBcc(getAddress(msg.getRecipients (Message.RecipientType.BCC))); try { mailInfo.setSendDate(msg.getSentDate()); } catch (Exception e) { e.printStackTrace(); } //備份郵件 mailInfo.setMailFileName(FileUtils.getTempFile(tempPath, "mail", ".eml")); OutputStream fo = new FileOutputStream (mailInfo.getMailFileName()); try{ ((Part)msg).writeTo(fo); }finally{ fo.close(); } extractAttachMent((Part)msg,mailInfo.getAttachFileNames (),mailInfo.getAttachFiles(),tempPath); if(isdelete){ msg.setFlag(Flags.Flag.DELETED, true); } mails.add(mailInfo); } } folder.close(true); }finally{ store.close(); } return(mails); } public static void main(String[] args) throws Exception { MailInfo mailInfo = new MailInfo(); String tempPath="E:\\workspace\\test\\temp"; InputStream fis = new FileInputStream ("E:\\workspace\\test\\mail8063.eml"); Session mailSession = Session.getDefaultInstance(System.getProperties(), null); MimeMessage msg = new MimeMessage(mailSession, fis); extractAttachMent((Part)msg,mailInfo.getAttachFileNames (),mailInfo.getAttachFiles(),tempPath); } }