欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java實現(xiàn)簡單發(fā)送郵件功能

 更新時間:2022年04月22日 10:26:17   作者:Yweir  
這篇文章主要為大家詳細介紹了java實現(xiàn)簡單發(fā)送郵件功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了java實現(xiàn)簡單發(fā)送郵件的具體代碼,供大家參考,具體內(nèi)容如下

添加依賴

<!--發(fā)送郵件API-->
? ? <!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
? ? <dependency>
? ? ? <groupId>javax.mail</groupId>
? ? ? <artifactId>javax.mail-api</artifactId>
? ? ? <version>1.6.2</version>
? ? </dependency>
? ? <!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
? ? <dependency>
? ? ? <groupId>com.sun.mail</groupId>
? ? ? <artifactId>javax.mail</artifactId>
? ? ? <version>1.6.2</version>
</dependency>

自定義異常類

public class EmailException extends Exception {

?? ?public EmailException(String message) {
?? ??? ?super(message);
?? ?}
?? ? public EmailException() {
?? ? ? ? ? ?super();
?? ? }
?? ?/**
?? ? *?
?? ? */
?? ?private static final long serialVersionUID = 115631651651651651L;

}

IMAP協(xié)議讀取郵件

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

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.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.sun.mail.util.MailSSLSocketFactory;


public class IMAPReceiveMail {
?? ?private String user = "";//賬號
?? ?private String password = "";//密碼
?? ?private ?String HOST = ""; // smtp服務器
//?? ?private Properties props = null;
?? ?private Folder folder = null;//收件箱
?? ?private Store store ?= null;//實例對象
//?? ?final String pop3 = "IMAP";
?? ?final String imap = "imap";
?? ?public IMAPReceiveMail(String user,String password) {
?? ??? ?this.password = password;//密碼
?? ??? ?this.user = user;//賬戶
?? ?}
?? ?
?? ? /**
?? ? * @param message 郵件對象
?? ? * @param to 收件人
?? ? * @throws MessagingException
?? ? * @throws IOException
?? ? */
//?? ?public void forwardMail(Message message,String to) throws MessagingException, IOException {
//?? ? ? ? ? ?Message forward = new MimeMessage(session);
//?? ? ? ? ? ?forward.setSubject(message.getSubject());
//?? ? ? ? ? ?forward.setFrom(new InternetAddress(to));
//?? ? ? ? ? ?forward.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
//?? ? ? ? ? ?forward.setSentDate(new Date());
//?? ? ? ? ? ?forward.setContent(message.getContent(), message.getContentType());
//
//?? ? ? ? ? ?Transport smtp = session.getTransport("smtp");
//?? ? ? ? ? ?smtp.connect(HOST, user, password);//連接服務器的郵箱
//?? ? ? ? ? ?smtp.sendMessage(forward, forward.getAllRecipients());
//?? ? ? ? ? ?smtp.close();
//?? ? }
?? ?/**
?? ? * 接收郵件
?? ? */
?? ?public ?Folder resceive() throws Exception {
?? ??? ?/**
?? ??? ? * 因為現(xiàn)在使用的是163郵箱 而163的 pop地址是 pop3.163.com 端口是 110 比如使用好未來企業(yè)郵箱 就需要換成 好未來郵箱的
?? ??? ? * pop服務器地址 pop.263.net 和 端口 110
?? ??? ? */
?? ??? ?String duankou = ""; // 端口號
?? ??? ?String servicePath = ""; // 服務器地址
?? ??? ?if(user==null||user.length()==0) throw new EmailException("賬戶不能為空?。。?!");
?? ??? ?if(password==null||password.length()==0) throw new EmailException("密碼不能為空?。。?!");
?? ??? ?if(user.contains("@163")) {
?? ??? ??? ?duankou = "143"; // 端口號
?? ??? ??? ?servicePath = "imap.163.com"; // 服務器地址
?? ??? ?}else if(user.contains("@qq")) {
?? ??? ??? ?duankou = "993"; // 端口號
?? ??? ??? ?servicePath = "imap.qq.com"; // 服務器地址
?? ??? ?}else {
?? ??? ??? ?throw new EmailException("不支持該協(xié)議");
?? ??? ?}

?? ??? ?// 準備連接服務器的會話信息
?? ??? ?Properties props = new Properties();
? ? ? ??
?? ??? ?props.setProperty("mail.store.protocol", imap); // 使用pop3協(xié)議
?? ??? ?props.setProperty("mail.imap.socketFactory.fallback", "false");
?? ??? ?props.setProperty("mail.imap.port", duankou); // 端口
?? ??? ?props.setProperty("mail.imap.socketFactory.port", duankou); // 端口
?? ??? ?props.setProperty("mail.transport.protocol", "smtp");// 發(fā)送郵件協(xié)議名稱
?? ? ? ?props.setProperty("mail.smtp.auth", "true"); ?//需要經(jīng)過授權,也就是有戶名和密碼的校驗,這樣才能通過驗證(一定要有這一條
?? ? ? ?props.setProperty("mail.host", HOST);
?? ??? ?
?? ??? ?//關閉讀取附件時分批獲取 BASE64 輸入流的配置
?? ??? ?props.setProperty("mail.imap.partialfetch", "false");
?? ??? ?props.setProperty("mail.imaps.partialfetch", "false");
//?? ??? ?props.setProperty("mail.pop3.host", servicePath); // pop3服務器
?? ??? ?
//?? ??? ?final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";?
// ? ? ? ?Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
//?? ??? ?props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
?? ??? ?MailSSLSocketFactory sf = new MailSSLSocketFactory();//ssl加密
? ? ? ? sf.setTrustAllHosts(true);
? ? ? ? props.put("mail.imap.ssl.enable", "true");
? ? ? ? props.put("mail.imap.ssl.socketFactory", sf);
? ? ? ??
?? ??? ?// 創(chuàng)建Session實例對象
? ? ? ? Session session = Session.getInstance(props);
?? ??? ?session.setDebug(false);
?? ??? ?store = session.getStore(imap);
?? ??? ?store.connect(servicePath,user,password); // 163郵箱程序登錄屬于第三方登錄所以這里的密碼是163給的授權密碼而并非普通的登錄密碼
?? ??? ?// 獲得收件箱
?? ??? ?folder = store.getFolder("INBOX");
?? ??? ?/*
?? ??? ? * Folder.READ_ONLY:只讀權限 Folder.READ_WRITE:可讀可寫(可以修改郵件的狀態(tài))
?? ??? ? */
?? ??? ?folder.open(Folder.READ_WRITE); // 打開收件箱
?? ??? ?// 由于POP3協(xié)議無法獲知郵件的狀態(tài),所以getUnreadMessageCount得到的是收件箱的郵件總數(shù)
//?? ??? ?System.out.println("未讀郵件數(shù): " + folder.getUnreadMessageCount());
?? ??? ?// 由于POP3協(xié)議無法獲知郵件的狀態(tài),所以下面得到的結(jié)果始終都是為0
//?? ??? ?System.out.println("刪除郵件數(shù): " + folder.getDeletedMessageCount());
//?? ??? ?System.out.println("新郵件: " + folder.getNewMessageCount());
?? ??? ?// 獲得收件箱中的郵件總數(shù)
//?? ??? ?System.out.println("郵件總數(shù): " + folder.getMessageCount());
?? ??? ?// 得到收件箱中的所有郵件,并解析
//?? ??? ?Message[] messages = folder.getMessages();
//?? ??? ?parseMessage(messages);
?? ??? ?// 得到收件箱中的所有郵件并且刪除郵件
//?? ??? ?deleteMessage(messages);

?? ??? ?// 釋放資源
//?? ??? ?folder.close(true);
//?? ??? ?store.close();
?? ??? ?return folder;
?? ?}
?? ?public void Colsefolder() throws MessagingException {//關閉資源
?? ??? ?if(folder!=null) {
?? ??? ??? ?folder.close();
?? ??? ?}
?? ??? ?if(store!=null) {
?? ??? ??? ?store.close();
?? ??? ?}
?? ?}
?? ?/**
?? ? * 解析郵件
?? ? *?
?? ? * @param messages 要解析的郵件列表
?? ? */
?? ?public ?void parseMessage(Message... messages) throws MessagingException, IOException {
?? ??? ?if (messages == null || messages.length < 1)
?? ??? ??? ?throw new MessagingException("未找到要解析的郵件!");
?? ??? ?// 解析所有郵件
?? ??? ?for (int i = 0, count = messages.length; i < count; i++) {
?? ??? ??? ?MimeMessage msg = (MimeMessage) messages[i];
?? ??? ??? ?System.out.println("------------------解析第" + msg.getMessageNumber() + "封郵件-------------------- ");
?? ??? ??? ?System.out.println("主題: " + getSubject(msg));
?? ??? ??? ?System.out.println("發(fā)件人: " + getFrom(msg));
?? ??? ??? ?System.out.println("收件人:" + getReceiveAddress(msg, null));
?? ??? ??? ?System.out.println("發(fā)送時間:" + getSentDate(msg, null));
?? ??? ??? ?System.out.println("是否已讀:" + isSeen(msg));
?? ??? ??? ?System.out.println("郵件優(yōu)先級:" + getPriority(msg));
?? ??? ??? ?System.out.println("是否需要回執(zhí):" + isReplySign(msg));
?? ??? ??? ?System.out.println("郵件大?。? + msg.getSize() * 1024 + "kb");
?? ??? ??? ?boolean isContainerAttachment = isContainAttachment(msg);
?? ??? ??? ?System.out.println("是否包含附件:" + isContainerAttachment);
?? ??? ??? ?if (isContainerAttachment) {
?? ??? ??? ??? ?saveAttachment(msg, "f:\\mailTest\\" + msg.getSubject() + "_" + i + "_"); // 保存附件
?? ??? ??? ?}
?? ??? ??? ?StringBuffer content = new StringBuffer(30);
?? ??? ??? ?getMailTextContent(msg, content);
?? ??? ??? ?System.out.println("郵件正文:" + (content.length() > 100 ? content.substring(0, 100) + "..." : content));
?? ??? ??? ?System.out.println("------------------第" + msg.getMessageNumber() + "封郵件解析結(jié)束-------------------- ");
?? ??? ??? ?System.out.println();
?? ??? ?}
?? ?}

?? ?/**
?? ? * 解析郵件
?? ? *?
?? ? * @param messages 要解析的郵件列表
?? ? */
?? ?public ?void deleteMessage(Message... messages) throws MessagingException, IOException {
?? ??? ?if (messages == null || messages.length < 1)
?? ??? ??? ?throw new MessagingException("未找到要解析的郵件!");

?? ??? ?// 解析所有郵件
?? ??? ?for (int i = 0, count = messages.length; i < count; i++) {

?? ??? ??? ?/**
?? ??? ??? ? * 郵件刪除
?? ??? ??? ? */
?? ??? ??? ?Message message = messages[i];
?? ??? ??? ?String subject = message.getSubject();
?? ??? ??? ?// set the DELETE flag to true
?? ??? ??? ?message.setFlag(Flags.Flag.DELETED, true);
?? ??? ??? ?System.out.println("Marked DELETE for message: " + subject);

?? ??? ?}
?? ?}

?? ?/**
?? ? * 獲得郵件主題
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return 解碼后的郵件主題
?? ? */
?? ?public ?String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
?? ??? ?return MimeUtility.decodeText(msg.getSubject());
?? ?}

?? ?/**
?? ? * 獲得郵件發(fā)件人
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return 姓名 <Email地址>
?? ? * @throws MessagingException
?? ? * @throws UnsupportedEncodingException
?? ? */
?? ?public ?String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
?? ??? ?String from = "";
?? ??? ?Address[] froms = msg.getFrom();
?? ??? ?if (froms.length < 1)
?? ??? ??? ?throw new MessagingException("沒有發(fā)件人!");

?? ??? ?InternetAddress address = (InternetAddress) froms[0];
?? ??? ?String person = address.getPersonal();
?? ??? ?if (person != null) {
?? ??? ??? ?person = MimeUtility.decodeText(person) + " ";
?? ??? ?} else {
?? ??? ??? ?person = "";
?? ??? ?}
?? ??? ?from = person + "<" + address.getAddress() + ">";

?? ??? ?return from;
?? ?}
?? ?
?? ?
?? ?public ?String getFromAddress(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
?? ??? ?String from = "";
?? ??? ?Address[] froms = msg.getFrom();
?? ??? ?if (froms.length < 1)
?? ??? ??? ?throw new MessagingException("沒有發(fā)件人!");

?? ??? ?InternetAddress address = (InternetAddress) froms[0];
?? ??? ?from = address.getAddress();

?? ??? ?return from;
?? ?}
?? ?/**
?? ? * 根據(jù)收件人類型,獲取郵件收件人、抄送和密送地址。如果收件人類型為空,則獲得所有的收件人
?? ? * <p>
?? ? * Message.RecipientType.TO 收件人
?? ? * </p>
?? ? * <p>
?? ? * Message.RecipientType.CC 抄送
?? ? * </p>
?? ? * <p>
?? ? * Message.RecipientType.BCC 密送
?? ? * </p>
?? ? *?
?? ? * @param msg ?郵件內(nèi)容
?? ? * @param type 收件人類型
?? ? * @return 收件人1 <郵件地址1>, 收件人2 <郵件地址2>, ...
?? ? * @throws MessagingException
?? ? */
?? ?public ?String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
?? ??? ?StringBuffer receiveAddress = new StringBuffer();
?? ??? ?Address[] addresss = null;
?? ??? ?if (type == null) {
?? ??? ??? ?addresss = msg.getAllRecipients();
?? ??? ?} else {
?? ??? ??? ?addresss = msg.getRecipients(type);
?? ??? ?}

?? ??? ?if (addresss == null || addresss.length < 1)
?? ??? ??? ?throw new MessagingException("沒有收件人!");
?? ??? ?for (Address address : addresss) {
?? ??? ??? ?InternetAddress internetAddress = (InternetAddress) address;
?? ??? ??? ?receiveAddress.append(internetAddress.toUnicodeString()).append(",");
?? ??? ?}

?? ??? ?receiveAddress.deleteCharAt(receiveAddress.length() - 1); // 刪除最后一個逗號

?? ??? ?return receiveAddress.toString();
?? ?}

?? ?/**
?? ? * 獲得郵件發(fā)送時間
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return yyyy年mm月dd日 星期X HH:mm
?? ? * @throws MessagingException
?? ? */
?? ?public ?String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
?? ??? ?Date receivedDate = msg.getSentDate();
?? ??? ?if (receivedDate == null)
?? ??? ??? ?return "";

?? ??? ?if (pattern == null || "".equals(pattern))
?? ??? ??? ?pattern = "yyyy年MM月dd日 E HH:mm ";

?? ??? ?return new SimpleDateFormat(pattern).format(receivedDate);
?? ?}

?? ?/**
?? ? * 判斷郵件中是否包含附件
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return 郵件中存在附件返回true,不存在返回false
?? ? * @throws MessagingException
?? ? * @throws IOException
?? ? */
?? ?public ?boolean isContainAttachment(Part part) throws MessagingException, IOException {
?? ??? ?boolean flag = false;
?? ??? ?if (part.isMimeType("multipart/*")) {
?? ??? ??? ?MimeMultipart multipart = (MimeMultipart) part.getContent();
?? ??? ??? ?int partCount = multipart.getCount();
?? ??? ??? ?for (int i = 0; i < partCount; i++) {
?? ??? ??? ??? ?BodyPart bodyPart = multipart.getBodyPart(i);
?? ??? ??? ??? ?String disp = bodyPart.getDisposition();
?? ??? ??? ??? ?if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
?? ??? ??? ??? ??? ?flag = true;
?? ??? ??? ??? ?} else if (bodyPart.isMimeType("multipart/*")) {
?? ??? ??? ??? ??? ?flag = isContainAttachment(bodyPart);
?? ??? ??? ??? ?} else {
?? ??? ??? ??? ??? ?String contentType = bodyPart.getContentType();
?? ??? ??? ??? ??? ?if (contentType.indexOf("application") != -1) {
?? ??? ??? ??? ??? ??? ?flag = true;
?? ??? ??? ??? ??? ?}

?? ??? ??? ??? ??? ?if (contentType.indexOf("name") != -1) {
?? ??? ??? ??? ??? ??? ?flag = true;
?? ??? ??? ??? ??? ?}
?? ??? ??? ??? ?}

?? ??? ??? ??? ?if (flag)
?? ??? ??? ??? ??? ?break;
?? ??? ??? ?}
?? ??? ?} else if (part.isMimeType("message/rfc822")) {
?? ??? ??? ?flag = isContainAttachment((Part) part.getContent());
?? ??? ?}
?? ??? ?return flag;
?? ?}

?? ?/**
?? ? * 判斷郵件是否已讀
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return 如果郵件已讀返回true,否則返回false
?? ? * @throws MessagingException
?? ? */
?? ?public ?boolean isSeen(MimeMessage msg) throws MessagingException {
?? ??? ?return msg.getFlags().contains(Flags.Flag.SEEN);
?? ?}

?? ?/**
?? ? * 判斷郵件是否需要閱讀回執(zhí)
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return 需要回執(zhí)返回true,否則返回false
?? ? * @throws MessagingException
?? ? */
?? ?public ?boolean isReplySign(MimeMessage msg) throws MessagingException {
?? ??? ?boolean replySign = false;
?? ??? ?String[] headers = msg.getHeader("Disposition-Notification-To");
?? ??? ?if (headers != null)
?? ??? ??? ?replySign = true;
?? ??? ?return replySign;
?? ?}

?? ?/**
?? ? * 獲得郵件的優(yōu)先級
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return 1(High):緊急 3:普通(Normal) 5:低(Low)
?? ? * @throws MessagingException
?? ? */
?? ?public ?String getPriority(MimeMessage msg) throws MessagingException {
?? ??? ?String priority = "普通";
?? ??? ?String[] headers = msg.getHeader("X-Priority");
?? ??? ?if (headers != null) {
?? ??? ??? ?String headerPriority = headers[0];
?? ??? ??? ?if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1)
?? ??? ??? ??? ?priority = "緊急";
?? ??? ??? ?else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1)
?? ??? ??? ??? ?priority = "低";
?? ??? ??? ?else
?? ??? ??? ??? ?priority = "普通";
?? ??? ?}
?? ??? ?return priority;
?? ?}

?? ?/**
?? ? * 獲得郵件文本內(nèi)容
?? ? *?
?? ? * @param part ? ?郵件體
?? ? * @param content 存儲郵件文本內(nèi)容的字符串
?? ? * @throws MessagingException
?? ? * @throws IOException
?? ? */
?? ?public ?void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
?? ??? ?// 如果是文本類型的附件,通過getContent方法可以取到文本內(nèi)容,但這不是我們需要的結(jié)果,所以在這里要做判斷
?? ??? ?boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
?? ??? ?if (part.isMimeType("text/*") && !isContainTextAttach) {
?? ??? ??? ?content.append(part.getContent().toString());
?? ??? ?} else if (part.isMimeType("message/rfc822")) {
?? ??? ??? ?getMailTextContent((Part) part.getContent(), content);
?? ??? ?} else if (part.isMimeType("multipart/*")) {
?? ??? ??? ?Multipart multipart = (Multipart) part.getContent();
?? ??? ??? ?int partCount = multipart.getCount();
?? ??? ??? ?for (int i = 0; i < partCount; i++) {
?? ??? ??? ??? ?BodyPart bodyPart = multipart.getBodyPart(i);
?? ??? ??? ??? ?getMailTextContent(bodyPart, content);
?? ??? ??? ?}
?? ??? ?}
?? ?}

?? ?/**
?? ? * 保存附件
?? ? *?
?? ? * @param part ? ?郵件中多個組合體中的其中一個組合體
?? ? * @param destDir 附件保存目錄
?? ? * @throws UnsupportedEncodingException
?? ? * @throws MessagingException
?? ? * @throws FileNotFoundException
?? ? * @throws IOException
?? ? */
?? ?public ?void saveAttachment(Part part, String destDir)
?? ??? ??? ?throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
?? ??? ?if (part.isMimeType("multipart/*")) {
?? ??? ??? ?Multipart multipart = (Multipart) part.getContent(); // 復雜體郵件
?? ??? ??? ?// 復雜體郵件包含多個郵件體
?? ??? ??? ?int partCount = multipart.getCount();
?? ??? ??? ?for (int i = 0; i < partCount; i++) {
?? ??? ??? ??? ?// 獲得復雜體郵件中其中一個郵件體
?? ??? ??? ??? ?BodyPart bodyPart = multipart.getBodyPart(i);
?? ??? ??? ??? ?// 某一個郵件體也有可能是由多個郵件體組成的復雜體
?? ??? ??? ??? ?String disp = bodyPart.getDisposition();
?? ??? ??? ??? ?if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
?? ??? ??? ??? ??? ?InputStream is = bodyPart.getInputStream();
?? ??? ??? ??? ??? ?saveFile(is, destDir, decodeText(bodyPart.getFileName()));
?? ??? ??? ??? ?} else if (bodyPart.isMimeType("multipart/*")) {
?? ??? ??? ??? ??? ?saveAttachment(bodyPart, destDir);
?? ??? ??? ??? ?} else {
?? ??? ??? ??? ??? ?String contentType = bodyPart.getContentType();
?? ??? ??? ??? ??? ?if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
?? ??? ??? ??? ??? ??? ?saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
?? ??? ??? ??? ??? ?}
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ?} else if (part.isMimeType("message/rfc822")) {
?? ??? ??? ?saveAttachment((Part) part.getContent(), destDir);
?? ??? ?}
?? ?}

?? ?/**
?? ? * 讀取輸入流中的數(shù)據(jù)保存至指定目錄
?? ? *?
?? ? * @param is ? ? ? 輸入流
?? ? * @param fileName 文件名
?? ? * @param destDir ?文件存儲目錄
?? ? * @throws FileNotFoundException
?? ? * @throws IOException
?? ? */
?? ?private ?void saveFile(InputStream is, String destDir, String fileName)
?? ??? ??? ?throws FileNotFoundException, IOException {
?? ??? ?BufferedInputStream bis = new BufferedInputStream(is);
?? ??? ?BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(destDir + fileName)));
?? ??? ?int len = -1;
?? ??? ?while ((len = bis.read()) != -1) {
?? ??? ??? ?bos.write(len);
?? ??? ??? ?bos.flush();
?? ??? ?}
?? ??? ?bos.close();
?? ??? ?bis.close();
?? ?}

?? ?public void SetSEEN(MimeMessage message) throws MessagingException {//設置文件已讀
?? ??? ?message.setFlag(Flags.Flag.SEEN,true);
?? ?}
?? ?/**
?? ? * 文本解碼
?? ? *?
?? ? * @param encodeText 解碼MimeUtility.encodeText(String text)方法編碼后的文本
?? ? * @return 解碼后的文本
?? ? * @throws UnsupportedEncodingException
?? ? */
?? ?public ?String decodeText(String encodeText) throws UnsupportedEncodingException {
?? ??? ?if (encodeText == null || "".equals(encodeText)) {
?? ??? ??? ?return "";
?? ??? ?} else {
?? ??? ??? ?return MimeUtility.decodeText(encodeText);
?? ??? ?}
?? ?}
}

POP3協(xié)議接收郵件

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

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.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.sun.mail.util.MailSSLSocketFactory;

/**
?* 使用POP3協(xié)議接收郵件
?*/
public class POP3ReceiveMail {
?? ?private String user = "";//賬號
?? ?private String password = "";//密碼
//?? ?private Properties props = null;
?? ?private Folder folder = null;//收件箱
?? ?private Store store ?= null;//實例對象
?? ?final String pop3 = "pop3";
//?? ?final String imap = "imap";
?? ?public POP3ReceiveMail(String user,String password) {
?? ??? ?this.password = password;//密碼
?? ??? ?this.user = user;//賬戶
?? ?}
?? ?/**
?? ? * 接收郵件
?? ? */
?? ?public ?Folder resceive() throws Exception {
?? ??? ?/**
?? ??? ? * 因為現(xiàn)在使用的是163郵箱 而163的 pop地址是 pop3.163.com 端口是 110 比如使用好未來企業(yè)郵箱 就需要換成 好未來郵箱的
?? ??? ? * pop服務器地址 pop.263.net 和 端口 110
?? ??? ? */
?? ??? ?
?? ??? ?String duankou = ""; // 端口號
?? ??? ?String servicePath = ""; // 服務器地址
?? ??? ?if(user==null||user.length()==0) throw new EmailException("賬戶不能為空?。。。?);
?? ??? ?if(password==null||password.length()==0) throw new EmailException("密碼不能為空?。。?!");
?? ??? ?if(user.contains("@163")) {
?? ??? ??? ?duankou = "110"; // 端口號
?? ??? ??? ?servicePath = "pop3.163.com"; // 服務器地址
?? ??? ?}else if(user.contains("@qq")) {
?? ??? ??? ?duankou = "995"; // 端口號
?? ??? ??? ?servicePath = "pop.qq.com"; // 服務器地址
?? ??? ?}else {
?? ??? ??? ?throw new EmailException("不支持該協(xié)議");
?? ??? ?}
?? ??? ?

?? ??? ?// 準備連接服務器的會話信息
?? ??? ?Properties props = new Properties();
?? ??? ?props.setProperty("mail.store.protocol", pop3); // 使用pop3協(xié)議

//?? ??? ?props.setProperty("mail.transport.protocol", pop3); // 使用pop3協(xié)議
?? ??? ?props.setProperty("mail.pop3.port", duankou); // 端口
?? ??? ?props.setProperty("mail.pop3.host", servicePath); // pop3服務器
?? ??? ?props.setProperty("mail.pop3.socketFactory.fallback", "true");
?? ??? ?
?? ??? ?MailSSLSocketFactory sf = new MailSSLSocketFactory();//ssl加密
? ? ? ? sf.setTrustAllHosts(true);
? ? ? ? props.put("mail.pop3.ssl.enable", "true");
? ? ? ? props.put("mail.pop3.ssl.socketFactory", sf);
? ? ? ??
//?? ??? ?final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";?
// ? ? ?Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
//?? ??? ?props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
?? ??? ?// 創(chuàng)建Session實例對象
?? ??? ?Session session = Session.getInstance(props);
?? ??? ?store = session.getStore(pop3);
?? ??? ?store.connect(servicePath,user,password); // 163郵箱程序登錄屬于第三方登錄所以這里的密碼是163給的授權密碼而并非普通的登錄密碼
?? ??? ?// 獲得收件箱
?? ??? ?folder = store.getFolder("INBOX");
?? ??? ?/*
?? ??? ? * Folder.READ_ONLY:只讀權限 Folder.READ_WRITE:可讀可寫(可以修改郵件的狀態(tài))
?? ??? ? */
//?? ??? ?folder.open(Folder.READ_WRITE); // 打開收件箱
?? ??? ?folder.open(Folder.READ_WRITE); // 打開收件箱
?? ??? ?// 由于POP3協(xié)議無法獲知郵件的狀態(tài),所以getUnreadMessageCount得到的是收件箱的郵件總數(shù)
//?? ??? ?System.out.println("未讀郵件數(shù): " + folder.getUnreadMessageCount());
?? ??? ?// 由于POP3協(xié)議無法獲知郵件的狀態(tài),所以下面得到的結(jié)果始終都是為0
//?? ??? ?System.out.println("刪除郵件數(shù): " + folder.getDeletedMessageCount());
//?? ??? ?System.out.println("新郵件: " + folder.getNewMessageCount());
?? ??? ?// 獲得收件箱中的郵件總數(shù)
//?? ??? ?System.out.println("郵件總數(shù): " + folder.getMessageCount());
?? ??? ?// 得到收件箱中的所有郵件,并解析
//?? ??? ?Message[] messages = folder.getMessages();
//?? ??? ?parseMessage(messages);
?? ??? ?// 得到收件箱中的所有郵件并且刪除郵件
//?? ??? ?deleteMessage(messages);

?? ??? ?// 釋放資源
//?? ??? ?folder.close(true);
//?? ??? ?store.close();
?? ??? ?return folder;
?? ?}
?? ?public void Colsefolder() throws MessagingException {//關閉資源
?? ??? ?if(folder!=null) {
?? ??? ??? ?folder.close();
?? ??? ?}
?? ??? ?if(store!=null) {
?? ??? ??? ?store.close();
?? ??? ?}
?? ?}
?? ?/**
?? ? * 解析郵件
?? ? *?
?? ? * @param messages 要解析的郵件列表
?? ? */
?? ?public ?void parseMessage(Message... messages) throws MessagingException, IOException {
?? ??? ?if (messages == null || messages.length < 1)
?? ??? ??? ?throw new MessagingException("未找到要解析的郵件!");
?? ??? ?// 解析所有郵件
?? ??? ?for (int i = 0, count = messages.length; i < count; i++) {
?? ??? ??? ?MimeMessage msg = (MimeMessage) messages[i];
?? ??? ??? ?System.out.println("------------------解析第" + msg.getMessageNumber() + "封郵件-------------------- ");
?? ??? ??? ?System.out.println("主題: " + getSubject(msg));
?? ??? ??? ?System.out.println("發(fā)件人: " + getFrom(msg));
?? ??? ??? ?System.out.println("收件人:" + getReceiveAddress(msg, null));
?? ??? ??? ?System.out.println("發(fā)送時間:" + getSentDate(msg, null));
?? ??? ??? ?System.out.println("是否已讀:" + isSeen(msg));
?? ??? ??? ?System.out.println("郵件優(yōu)先級:" + getPriority(msg));
?? ??? ??? ?System.out.println("是否需要回執(zhí):" + isReplySign(msg));
?? ??? ??? ?System.out.println("郵件大?。? + msg.getSize() * 1024 + "kb");
?? ??? ??? ?boolean isContainerAttachment = isContainAttachment(msg);
?? ??? ??? ?System.out.println("是否包含附件:" + isContainerAttachment);
?? ??? ??? ?if (isContainerAttachment) {
?? ??? ??? ??? ?saveAttachment(msg, "f:\\mailTest\\" + msg.getSubject() + "_" + i + "_"); // 保存附件
?? ??? ??? ?}
?? ??? ??? ?StringBuffer content = new StringBuffer(30);
?? ??? ??? ?getMailTextContent(msg, content);
?? ??? ??? ?System.out.println("郵件正文:" + (content.length() > 100 ? content.substring(0, 100) + "..." : content));
?? ??? ??? ?System.out.println("------------------第" + msg.getMessageNumber() + "封郵件解析結(jié)束-------------------- ");
?? ??? ??? ?System.out.println();
?? ??? ?}
?? ?}

?? ?/**
?? ? * 解析郵件
?? ? *?
?? ? * @param messages 要解析的郵件列表
?? ? */
?? ?public ?void deleteMessage(Message... messages) throws MessagingException, IOException {
?? ??? ?if (messages == null || messages.length < 1)
?? ??? ??? ?throw new MessagingException("未找到要解析的郵件!");

?? ??? ?// 解析所有郵件
?? ??? ?for (int i = 0, count = messages.length; i < count; i++) {

?? ??? ??? ?/**
?? ??? ??? ? * 郵件刪除
?? ??? ??? ? */
?? ??? ??? ?Message message = messages[i];
?? ??? ??? ?String subject = message.getSubject();
?? ??? ??? ?// set the DELETE flag to true
?? ??? ??? ?message.setFlag(Flags.Flag.DELETED, true);
?? ??? ??? ?System.out.println("Marked DELETE for message: " + subject);

?? ??? ?}
?? ?}

?? ?/**
?? ? * 獲得郵件主題
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return 解碼后的郵件主題
?? ? */
?? ?public ?String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
?? ??? ?return MimeUtility.decodeText(msg.getSubject());
?? ?}

?? ?/**
?? ? * 獲得郵件發(fā)件人
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return 姓名 <Email地址>
?? ? * @throws MessagingException
?? ? * @throws UnsupportedEncodingException
?? ? */
?? ?public ?String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
?? ??? ?String from = "";
?? ??? ?Address[] froms = msg.getFrom();
?? ??? ?if (froms.length < 1)
?? ??? ??? ?throw new MessagingException("沒有發(fā)件人!");

?? ??? ?InternetAddress address = (InternetAddress) froms[0];
?? ??? ?String person = address.getPersonal();
?? ??? ?if (person != null) {
?? ??? ??? ?person = MimeUtility.decodeText(person) + " ";
?? ??? ?} else {
?? ??? ??? ?person = "";
?? ??? ?}
?? ??? ?from = person + "<" + address.getAddress() + ">";

?? ??? ?return from;
?? ?}

?? ?public ?String getFromAddress(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
?? ??? ?String from = "";
?? ??? ?Address[] froms = msg.getFrom();
?? ??? ?if (froms.length < 1)
?? ??? ??? ?throw new MessagingException("沒有發(fā)件人!");

?? ??? ?InternetAddress address = (InternetAddress) froms[0];
?? ??? ?from = address.getAddress();

?? ??? ?return from;
?? ?}
?? ?/**
?? ? * 根據(jù)收件人類型,獲取郵件收件人、抄送和密送地址。如果收件人類型為空,則獲得所有的收件人
?? ? * <p>
?? ? * Message.RecipientType.TO 收件人
?? ? * </p>
?? ? * <p>
?? ? * Message.RecipientType.CC 抄送
?? ? * </p>
?? ? * <p>
?? ? * Message.RecipientType.BCC 密送
?? ? * </p>
?? ? *?
?? ? * @param msg ?郵件內(nèi)容
?? ? * @param type 收件人類型
?? ? * @return 收件人1 <郵件地址1>, 收件人2 <郵件地址2>, ...
?? ? * @throws MessagingException
?? ? */
?? ?public ?String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
?? ??? ?StringBuffer receiveAddress = new StringBuffer();
?? ??? ?Address[] addresss = null;
?? ??? ?if (type == null) {
?? ??? ??? ?addresss = msg.getAllRecipients();
?? ??? ?} else {
?? ??? ??? ?addresss = msg.getRecipients(type);
?? ??? ?}

?? ??? ?if (addresss == null || addresss.length < 1)
?? ??? ??? ?throw new MessagingException("沒有收件人!");
?? ??? ?for (Address address : addresss) {
?? ??? ??? ?InternetAddress internetAddress = (InternetAddress) address;
?? ??? ??? ?receiveAddress.append(internetAddress.toUnicodeString()).append(",");
?? ??? ?}

?? ??? ?receiveAddress.deleteCharAt(receiveAddress.length() - 1); // 刪除最后一個逗號

?? ??? ?return receiveAddress.toString();
?? ?}

?? ?/**
?? ? * 獲得郵件發(fā)送時間
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return yyyy年mm月dd日 星期X HH:mm
?? ? * @throws MessagingException
?? ? */
?? ?public ?String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
?? ??? ?Date receivedDate = msg.getSentDate();
?? ??? ?if (receivedDate == null)
?? ??? ??? ?return "";

?? ??? ?if (pattern == null || "".equals(pattern))
?? ??? ??? ?pattern = "yyyy年MM月dd日 E HH:mm ";

?? ??? ?return new SimpleDateFormat(pattern).format(receivedDate);
?? ?}

?? ?/**
?? ? * 判斷郵件中是否包含附件
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return 郵件中存在附件返回true,不存在返回false
?? ? * @throws MessagingException
?? ? * @throws IOException
?? ? */
?? ?public ?boolean isContainAttachment(Part part) throws MessagingException, IOException {
?? ??? ?boolean flag = false;
?? ??? ?if (part.isMimeType("multipart/*")) {
?? ??? ??? ?MimeMultipart multipart = (MimeMultipart) part.getContent();
?? ??? ??? ?int partCount = multipart.getCount();
?? ??? ??? ?for (int i = 0; i < partCount; i++) {
?? ??? ??? ??? ?BodyPart bodyPart = multipart.getBodyPart(i);
?? ??? ??? ??? ?String disp = bodyPart.getDisposition();
?? ??? ??? ??? ?if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
?? ??? ??? ??? ??? ?flag = true;
?? ??? ??? ??? ?} else if (bodyPart.isMimeType("multipart/*")) {
?? ??? ??? ??? ??? ?flag = isContainAttachment(bodyPart);
?? ??? ??? ??? ?} else {
?? ??? ??? ??? ??? ?String contentType = bodyPart.getContentType();
?? ??? ??? ??? ??? ?if (contentType.indexOf("application") != -1) {
?? ??? ??? ??? ??? ??? ?flag = true;
?? ??? ??? ??? ??? ?}

?? ??? ??? ??? ??? ?if (contentType.indexOf("name") != -1) {
?? ??? ??? ??? ??? ??? ?flag = true;
?? ??? ??? ??? ??? ?}
?? ??? ??? ??? ?}

?? ??? ??? ??? ?if (flag)
?? ??? ??? ??? ??? ?break;
?? ??? ??? ?}
?? ??? ?} else if (part.isMimeType("message/rfc822")) {
?? ??? ??? ?flag = isContainAttachment((Part) part.getContent());
?? ??? ?}
?? ??? ?return flag;
?? ?}

?? ?/**
?? ? * 判斷郵件是否已讀
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return 如果郵件已讀返回true,否則返回false
?? ? * @throws MessagingException
?? ? */
?? ?public ?boolean isSeen(MimeMessage msg) throws MessagingException {
?? ??? ?return msg.getFlags().contains(Flags.Flag.SEEN);
?? ?}

?? ?/**
?? ? * 判斷郵件是否需要閱讀回執(zhí)
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return 需要回執(zhí)返回true,否則返回false
?? ? * @throws MessagingException
?? ? */
?? ?public ?boolean isReplySign(MimeMessage msg) throws MessagingException {
?? ??? ?boolean replySign = false;
?? ??? ?String[] headers = msg.getHeader("Disposition-Notification-To");
?? ??? ?if (headers != null)
?? ??? ??? ?replySign = true;
?? ??? ?return replySign;
?? ?}

?? ?/**
?? ? * 獲得郵件的優(yōu)先級
?? ? *?
?? ? * @param msg 郵件內(nèi)容
?? ? * @return 1(High):緊急 3:普通(Normal) 5:低(Low)
?? ? * @throws MessagingException
?? ? */
?? ?public ?String getPriority(MimeMessage msg) throws MessagingException {
?? ??? ?String priority = "普通";
?? ??? ?String[] headers = msg.getHeader("X-Priority");
?? ??? ?if (headers != null) {
?? ??? ??? ?String headerPriority = headers[0];
?? ??? ??? ?if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1)
?? ??? ??? ??? ?priority = "緊急";
?? ??? ??? ?else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1)
?? ??? ??? ??? ?priority = "低";
?? ??? ??? ?else
?? ??? ??? ??? ?priority = "普通";
?? ??? ?}
?? ??? ?return priority;
?? ?}

?? ?/**
?? ? * 獲得郵件文本內(nèi)容
?? ? *?
?? ? * @param part ? ?郵件體
?? ? * @param content 存儲郵件文本內(nèi)容的字符串
?? ? * @throws MessagingException
?? ? * @throws IOException
?? ? */
?? ?public ?void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
?? ??? ?// 如果是文本類型的附件,通過getContent方法可以取到文本內(nèi)容,但這不是我們需要的結(jié)果,所以在這里要做判斷
?? ??? ?boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
?? ??? ?if (part.isMimeType("text/*") && !isContainTextAttach) {
?? ??? ??? ?content.append(part.getContent().toString());
?? ??? ?} else if (part.isMimeType("message/rfc822")) {
?? ??? ??? ?getMailTextContent((Part) part.getContent(), content);
?? ??? ?} else if (part.isMimeType("multipart/*")) {
?? ??? ??? ?Multipart multipart = (Multipart) part.getContent();
?? ??? ??? ?int partCount = multipart.getCount();
?? ??? ??? ?for (int i = 0; i < partCount; i++) {
?? ??? ??? ??? ?BodyPart bodyPart = multipart.getBodyPart(i);
?? ??? ??? ??? ?getMailTextContent(bodyPart, content);
?? ??? ??? ?}
?? ??? ?}
?? ?}

?? ?/**
?? ? * 保存附件
?? ? *?
?? ? * @param part ? ?郵件中多個組合體中的其中一個組合體
?? ? * @param destDir 附件保存目錄
?? ? * @throws UnsupportedEncodingException
?? ? * @throws MessagingException
?? ? * @throws FileNotFoundException
?? ? * @throws IOException
?? ? */
?? ?public ?void saveAttachment(Part part, String destDir)
?? ??? ??? ?throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
?? ??? ?if (part.isMimeType("multipart/*")) {
?? ??? ??? ?Multipart multipart = (Multipart) part.getContent(); // 復雜體郵件
?? ??? ??? ?// 復雜體郵件包含多個郵件體
?? ??? ??? ?int partCount = multipart.getCount();
?? ??? ??? ?for (int i = 0; i < partCount; i++) {
?? ??? ??? ??? ?// 獲得復雜體郵件中其中一個郵件體
?? ??? ??? ??? ?BodyPart bodyPart = multipart.getBodyPart(i);
?? ??? ??? ??? ?// 某一個郵件體也有可能是由多個郵件體組成的復雜體
?? ??? ??? ??? ?String disp = bodyPart.getDisposition();
?? ??? ??? ??? ?if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
?? ??? ??? ??? ??? ?InputStream is = bodyPart.getInputStream();
?? ??? ??? ??? ??? ?saveFile(is, destDir, decodeText(bodyPart.getFileName()));
?? ??? ??? ??? ?} else if (bodyPart.isMimeType("multipart/*")) {
?? ??? ??? ??? ??? ?saveAttachment(bodyPart, destDir);
?? ??? ??? ??? ?} else {
?? ??? ??? ??? ??? ?String contentType = bodyPart.getContentType();
?? ??? ??? ??? ??? ?if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
?? ??? ??? ??? ??? ??? ?saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
?? ??? ??? ??? ??? ?}
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ?} else if (part.isMimeType("message/rfc822")) {
?? ??? ??? ?saveAttachment((Part) part.getContent(), destDir);
?? ??? ?}
?? ?}

?? ?/**
?? ? * 讀取輸入流中的數(shù)據(jù)保存至指定目錄
?? ? *?
?? ? * @param is ? ? ? 輸入流
?? ? * @param fileName 文件名
?? ? * @param destDir ?文件存儲目錄
?? ? * @throws FileNotFoundException
?? ? * @throws IOException
?? ? */
?? ?private ?void saveFile(InputStream is, String destDir, String fileName)
?? ??? ??? ?throws FileNotFoundException, IOException {
?? ??? ?BufferedInputStream bis = new BufferedInputStream(is);
?? ??? ?BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(destDir + fileName)));
?? ??? ?int len = -1;
?? ??? ?while ((len = bis.read()) != -1) {
?? ??? ??? ?bos.write(len);
?? ??? ??? ?bos.flush();
?? ??? ?}
?? ??? ?bos.close();
?? ??? ?bis.close();
?? ?}

?? ?/**
?? ? * 文本解碼
?? ? *?
?? ? * @param encodeText 解碼MimeUtility.encodeText(String text)方法編碼后的文本
?? ? * @return 解碼后的文本
?? ? * @throws UnsupportedEncodingException
?? ? */
?? ?public ?String decodeText(String encodeText) throws UnsupportedEncodingException {
?? ??? ?if (encodeText == null || "".equals(encodeText)) {
?? ??? ??? ?return "";
?? ??? ?} else {
?? ??? ??? ?return MimeUtility.decodeText(encodeText);
?? ??? ?}
?? ?}
}

發(fā)送郵件

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
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.sun.mail.util.MailSSLSocketFactory;

/*
?* 發(fā)送郵件
?*/
public class SendMailUtil {
?? ?private ?String HOST = ""; // smtp服務器
?? ?private String FROM = ""; // 發(fā)件人地址
//?? ?private String TO = ""; // 收件人地址
?? ?private String[] AFFIX = null; // 附件地址
// ? ?private String AFFIXNAME = ""; // 附件名稱
? ? private String USER = ""; // 用戶名
? ? private String PWD = ""; // 163的授權碼
// ? ?private String SUBJECT = ""; // 郵件標題
? ? private String[] TOS = null;
? ? private ?Properties props = null;//
? ? /**
? ? ?* @param USER 賬戶名
? ? ?* @param PWD?? ?密碼
? ? ?* @param FROM 發(fā)件人地址
? ? ?* @throws EmailException?
? ? ?* @throws GeneralSecurityException?
? ? ?*/
? ? public SendMailUtil(String USER,String PWD,String FROM) throws EmailException, GeneralSecurityException {
? ? ?? ?this.USER = USER;//賬戶
? ? ?? ?this.PWD = PWD;//密碼
? ? ?? ?this.FROM = FROM;//發(fā)件人地址
? ? ?? ?stratProperties();
? ? ?? ?
? ? }
? ? private void stratProperties() throws EmailException, GeneralSecurityException {
? ? ?? ? props = new Properties();
? ? ??? ?if(USER==null||USER.length()==0) {
? ? ??? ??? ?throw new EmailException("郵箱賬號不能為空");?? ?
? ? ??? ?}else {
? ? ??? ??? ?if(USER.contains("@qq")) {
? ? ??? ??? ??? ?HOST = "smtp.qq.com";
? ? ??? ??? ?}else if(USER.contains("@163")) {
? ? ??? ??? ??? ?HOST = "smtp.163.com";
? ? ??? ??? ?}else if(USER.contains("@sina")) {
? ? ??? ??? ??? ?HOST = "smtp.sina.com.cn";
? ? ??? ??? ?}else {
? ? ??? ??? ??? ?throw new EmailException("不支持該協(xié)議");
? ? ??? ??? ?}
// ? ? ?? ??? ?props.setProperty("mail.smtp.host", HOST);//設置發(fā)送郵件的郵件服務器的屬性(這里使用網(wǎng)易的smtp服務器)
? ? ??? ??? ?// 設置郵件服務器主機名
? ? ??? ??? ?props.setProperty("mail.host", HOST);
? ? ??? ? ? ?
? ? ??? ?}
? ? ??? ?if(PWD==null||PWD.length()==0)throw new EmailException("郵箱密碼不能為空");
? ? ??? ? props.setProperty("mail.transport.protocol", "smtp");// 發(fā)送郵件協(xié)議名稱
? ? ??? ?props.setProperty("mail.smtp.auth", "true"); ?//需要經(jīng)過授權,也就是有戶名和密碼的校驗,這樣才能通過驗證(一定要有這一條)
// ? ? ?? ?props.put("mail.debug", "true");//設置debug模式 后臺輸出郵件發(fā)送的過程
? ? ??? ?
? ? ??? ?MailSSLSocketFactory sf = new MailSSLSocketFactory();//ssl加密
? ? ? ? ?sf.setTrustAllHosts(true);
? ? ? ? ?props.put("mail.smtp.ssl.enable", "true");
? ? ? ? ?props.put("mail.smtp.ssl.socketFactory", sf);
? ? }
? ??
? ? public void forwardMail(Message message) throws AddressException, MessagingException, EmailException, IOException {
? ? ?? ?if(TOS.length==0)throw new EmailException("收件人不能為空");
? ? ?? ? Session session = Session.getInstance(props);//用props對象構建一個session
// ?? ? ? ?session.setDebug(true);//關閉控制臺輸出
??? ? ? ?MimeMessage newmessage = new MimeMessage(session);//用session為參數(shù)定義消息對象
??? ? ? ?newmessage.setSubject(message.getSubject());
??? ? ? ?? ?newmessage.setFrom(new InternetAddress(FROM));
??? ? ?? ?newmessage.setSentDate(new Date());
??? ??? ?newmessage.setContent(message.getContent(), message.getContentType());
??? ? ? ?InternetAddress[] sendTo = new InternetAddress[TOS.length]; // 加載收件人地址
??? ? ? ?for (int i = 0; i < TOS.length; i++) { ?
? ? ? ? ? ? ?sendTo[i] = new InternetAddress(TOS[i]); ?
? ? ? ? ?}
??? ? ? newmessage.addRecipients(Message.RecipientType.TO,sendTo);
??? ? ? newmessage.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(FROM));//設置在發(fā)送給收信人之前給自己(發(fā)送方)抄送一份,不然會被當成垃圾郵件,報554錯
??? ? ? Transport smtp = session.getTransport("smtp");
? ? ? ?smtp.connect(HOST, USER, PWD);
? ? ? ?smtp.sendMessage(newmessage, newmessage.getAllRecipients());
? ? ? ?smtp.close();
? ? }
? ? /**
? ? ?* @param path 需要添加附件的文件路徑
? ? ?* @throws EmailException?
? ? ?*/
? ? public void addFile(String...path) throws EmailException {
? ? ?? ?if(path==null||path.length==0)throw new EmailException("附件路徑不能為空");?? ?
? ? ?? ?this.AFFIX = path;
? ? }
? ? public void setTo(String...to) throws EmailException {
? ? ?? ?if(toString().length()>0) {
? ? ?? ??? ?for(String t : to) {
? ? ?? ??? ??? ?boolean emailFormat = emailFormat(t);
? ? ?? ??? ??? ?if(!emailFormat) {
? ? ?? ??? ??? ??? ?throw new EmailException(t+"郵箱格式不正確");?? ?
? ? ?? ??? ??? ?}
? ? ?? ??? ?}
? ? ?? ??? ?TOS = to;
? ? ?? ?}else {
? ? ?? ??? ?throw new EmailException("收件人不能為空");?? ?
? ? ?? ?}
? ? }
? ?
? ? /**
? ? ?** 驗證輸入的郵箱格式是否符合
? ? ?* @param email
? ? ?* @return 是否合法
? ? ?*/
? ? private ?boolean emailFormat(String email)
? ? {
? ? ? ? boolean tag = true;
? ? ? ? final String pattern1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
? ? ? ? final Pattern pattern = Pattern.compile(pattern1);
? ? ? ? final Matcher mat = pattern.matcher(email);
? ? ? ? if (!mat.find()) {
? ? ? ? ? ? tag = false;
? ? ? ? }
? ? ? ? return tag;
? ? }
? ? /**
? ? ?* @param SUBJECT 標題
? ? ?* @param context 文本信息
? ? ?* @throws EmailException
? ? ?* @throws MessagingException?
? ? ?* @throws AddressException?
? ? ?* @throws GeneralSecurityException?
? ? ?* @throws UnsupportedEncodingException?
? ? ?*/
? ? public ?void send(String SUBJECT,String context) throws EmailException, AddressException, MessagingException, GeneralSecurityException, UnsupportedEncodingException {
? ? ?? ?
? ? ?? ?if(SUBJECT==null||SUBJECT.length()==0)SUBJECT=UUID.randomUUID().toString();
// ? ??? ?this.SUBJECT = SUBJECT;//標題
? ? ?? ?if(TOS.length==0)throw new EmailException("收件人不能為空");
?? ? ? ?Session session = Session.getInstance(props);//用props對象構建一個session
//?? ? ? ?session.setDebug(true);//關閉控制臺輸出
?? ? ? ?MimeMessage message = new MimeMessage(session);//用session為參數(shù)定義消息對象
?? ? ? ?message.setFrom(new InternetAddress(FROM));// 加載發(fā)件人地址
?? ? ? ?InternetAddress[] sendTo = new InternetAddress[TOS.length]; // 加載收件人地址
?? ? ? ?for (int i = 0; i < TOS.length; i++) { ?
? ? ? ? ? ? sendTo[i] = new InternetAddress(TOS[i]); ?
? ? ? ? }
?? ? ? ?message.addRecipients(Message.RecipientType.TO,sendTo);
?? ? ? ?message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(FROM));//設置在發(fā)送給收信人之前給自己(發(fā)送方)抄送一份,不然會被當成垃圾郵件,報554錯
?? ? ? ?message.setSubject(SUBJECT);//加載標題
?? ? ? ?Multipart multipart = new MimeMultipart();//向multipart對象中添加郵件的各個部分內(nèi)容,包括文本內(nèi)容和附件
?? ? ? ?BodyPart contentPart = new MimeBodyPart();//設置郵件的文本內(nèi)容
? ? ? ? contentPart.setText(context);
? ? ? ? multipart.addBodyPart(contentPart);
? ? ? ? if(AFFIX!=null&&AFFIX.length>0){//添加附件
? ? ? ? ?? ?for(int i = 0 ; i <AFFIX.length ; i++) {
? ? ? ? ?? ??? ?File file = new File(AFFIX[i]);
? ? ? ? ?? ??? ?if(file.exists()) {
? ? ? ? ?? ??? ??? ? BodyPart messageBodyPart = new MimeBodyPart();
? ? ? ? ?? ??? ??? ? FileDataSource source = new FileDataSource(file);
// ? ? ? ? ? ? ? ? ? ? String AFFIXNAME = file.getName();
// ? ? ? ? ? ? ? ? ? ? System.out.println(AFFIXNAME);
? ? ? ? ? ? ? ? ? ? ?messageBodyPart.setDataHandler(new DataHandler(source));//添加附件的內(nèi)容
? ? ? ? ? ? ? ? ? ? ?messageBodyPart.setFileName(MimeUtility.encodeWord(file.getName(), "GBK", null));
? ? ? ? ? ? ? ? ? ? ?multipart.addBodyPart(messageBodyPart);
? ? ? ? ?? ??? ?}else {
? ? ? ? ?? ??? ??? ?throw new EmailException("文件"+AFFIX[i]+"不存在");
? ? ? ? ?? ??? ?}
? ? ? ? ?? ?}
? ? ? ? ? ??
? ? ? ? }
? ? ? ? message.setContent(multipart);//將multipart對象放到message中
? ? ? ? message.saveChanges(); //保存郵件
? ? ? ? Transport transport = session.getTransport();//發(fā)送郵件
? ? ? ? transport.connect(HOST, USER, PWD);//連接服務器的郵箱
? ? ? ? transport.sendMessage(message, message.getAllRecipients());//把郵件發(fā)送出去
? ? ? ? transport.close();//關閉連接
? ? }
}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • Java實現(xiàn)象棋算法的示例代碼

    Java實現(xiàn)象棋算法的示例代碼

    象棋算法包括搜索算法、評估函數(shù)和剪枝算法,本文主要介紹了Java實現(xiàn)象棋算法的示例代碼,具有一定的參考價值,感興趣的可以了解一下
    2023-12-12
  • Java定義形式及可變參數(shù)實例解析

    Java定義形式及可變參數(shù)實例解析

    這篇文章主要介紹了Java定義形式及可變參數(shù)實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-12-12
  • SpringCloud Eureka搭建的方法步驟

    SpringCloud Eureka搭建的方法步驟

    這篇文章主要介紹了SpringCloud Eureka搭建的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-01-01
  • Java軟件編程培訓機構靠譜嗎

    Java軟件編程培訓機構靠譜嗎

    隨著網(wǎng)絡信息化的快速發(fā)展,Java培訓受到越來越多人的青睞,目前Java工程師的薪資水平在不斷攀升,但是有好多企業(yè)還是招不到合適的人才,為什么呢
    2017-04-04
  • SpringBoot如何優(yōu)雅實現(xiàn)接口參數(shù)驗證

    SpringBoot如何優(yōu)雅實現(xiàn)接口參數(shù)驗證

    為了保證參數(shù)的正確性,我們需要使用參數(shù)驗證機制,來檢測并處理傳入的參數(shù)格式是否符合規(guī)范,所以本文就來和大家聊聊如何優(yōu)雅實現(xiàn)接口參數(shù)驗證吧
    2023-08-08
  • Java?超詳細帶你掌握矩陣的運算

    Java?超詳細帶你掌握矩陣的運算

    在學習機器學習算法時,發(fā)現(xiàn)運用java?來實現(xiàn)有些算法代碼時,會有很大困難,其中有一點就是?java?本身并沒有矩陣運算的?api,所以進行要實現(xiàn)矩陣運算就尤其復雜,讓我們一起了解矩陣的運算
    2022-03-03
  • 解決springboot利用ConfigurationProperties注解配置數(shù)據(jù)源無法讀取配置信息問題

    解決springboot利用ConfigurationProperties注解配置數(shù)據(jù)源無法讀取配置信息問題

    今天在學習springboot利用ConfigurationProperties注解配置數(shù)據(jù)源的使用遇到一個問題無法讀取配置信息,發(fā)現(xiàn)全部為null,糾結(jié)是哪里出了問題呢,今天一番思考,問題根源找到,下面把我的解決方案分享到腳本之家平臺,感興趣的朋友一起看看吧
    2021-05-05
  • Zookeeper連接超時問題與拒絕連接的解決方案

    Zookeeper連接超時問題與拒絕連接的解決方案

    今天小編就為大家分享一篇關于Zookeeper連接超時問題與拒絕連接的解決方案,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • java利用Future實現(xiàn)多線程執(zhí)行與結(jié)果聚合實例代碼

    java利用Future實現(xiàn)多線程執(zhí)行與結(jié)果聚合實例代碼

    這篇文章主要給大家介紹了關于java利用Future實現(xiàn)多線程執(zhí)行與結(jié)果聚合的相關資料,Future模式的核心,去除了主函數(shù)的等待時間,并使得原本需要等待的時間段可以用于處理其他業(yè)務邏輯,需要的朋友可以參考下
    2021-12-12
  • idea maven 構建本地jar包及pom文件的過程

    idea maven 構建本地jar包及pom文件的過程

    這篇文章主要介紹了idea maven 構建本地jar包及pom文件的過程,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2023-11-11

最新評論