因為公司內部辦公系統(OA)需要增加一個發送郵件的功能,所以學習了這個感覺比較冷門的JavaMail
1、先上成功截圖 :
2、准備事項:Java Mail雖然是官方寫的,但是沒有集成到jdk里面,所以需要自己下jar包
首先去官網下載,或者去CSDN 下(http://download.csdn.net/download/itsonglin/8632453)
ps:老版本的api似乎不支持開啟加密,建議去官網下最新jar包
3、這里貼一個封裝好了的工具類代碼,可以直接copy不用看,使用這個就能很方便的使用 javamail 而不用了解什么是javamail
ps:以前在學校學東西都是一步步的穩打穩扎,現在工作就是會用就行,趕快把功能做出來 , 唉,希望能有時間補起來
import com.sun.mail.util.MailSSLSocketFactory; import java.io.*; import java.security.GeneralSecurityException; import java.util.*; import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; public class SendMail { private String username = null; private String password = null; private Authenticator auth = null; private MimeMessage mimeMessage =null; private Properties pros = null; private Multipart multipart = null; private BodyPart bodypart= null; /** * 初始化賬號密碼並驗證 * 創建MimeMessage對象 * 發送郵件必須的步驟:1 * @param username * @param password */ public SendMail(String username,String password){ this.username = username; this.password = password; } /** * 設置email系統參數 * 接收一個map集合key為string類型,值為String * 發送郵件必須的步驟:2 * @param map */ public void setPros(Map<String,String> map){ pros = new Properties(); for(Map.Entry<String,String> entry:map.entrySet()){ pros.setProperty(entry.getKey(), entry.getValue()); } } /** * 初始化MimeMessage對象 * 發送郵件必須的步驟:3 */ public void initMessage(){ this.auth = new Email_Autherticator(); Session session = Session.getDefaultInstance(pros,auth); mimeMessage = new MimeMessage(session); } /** * 驗證賬號密碼 * 發送郵件必須的步驟 * @author Administrator * */ public class Email_Autherticator extends Authenticator { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } } /** * 設置發送郵件的基本參數(去除繁瑣的郵件設置) * @param sub 設置郵件主題 * @param text 設置郵件文本內容 * @param rec 設置郵件接收人 * @throws MessagingException * @throws UnsupportedEncodingException */ public void setDefaultMessagePros(String sub,String text,String rec) throws MessagingException, UnsupportedEncodingException{ mimeMessage.setSubject(sub); mimeMessage.setText(text); mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(rec)); mimeMessage.setSentDate(new Date()); mimeMessage.setFrom(new InternetAddress(username,username)); } /** * 設置主題 * @param subject * @throws MessagingException */ public void setSubject(String subject) throws MessagingException{ mimeMessage.setSubject(subject); } /** * 設置日期 * @param date * @throws MessagingException */ public void setDate(Date date) throws MessagingException{ mimeMessage.setSentDate(new Date()); } /** * 設置郵件文本內容 * @param text * @throws MessagingException */ public void setText(String text) throws MessagingException{ mimeMessage.setText(text); } /** * 設置郵件頭部 * @param arg0 * @param arg1 * @throws MessagingException */ public void setHeader(String arg0,String arg1) throws MessagingException{ mimeMessage.setHeader(arg0, arg1); } /** * 設置郵件接收人地址 <單人發送> * @param recipient * @throws MessagingException */ public void setRecipient(String recipient) throws MessagingException{ mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); } /** * 設置郵件接收人地址 <多人發送> * @param list * @throws MessagingException * @throws AddressException */ public String setRecipients(List<String> recs) throws AddressException, MessagingException{ if(recs.isEmpty()){ return "接收人地址為空!"; } for(String str:recs){ mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(str)); } return "加入接收人地址成功!"; } /** * 設置郵件接收人地址 <多人發送> * @param StringBuffer<parms,parms2,parms.....> * @throws MessagingException * @throws AddressException */ @SuppressWarnings("static-access") public String setRecipients(StringBuffer sb) throws AddressException, MessagingException{ if(sb==null||"".equals(sb)){ return "字符串數據為空!"; } Address []address = new InternetAddress().parse(sb.toString()); mimeMessage.addRecipients(Message.RecipientType.TO, address); return "收件人加入成功"; } /** * 設置郵件發送人的名字 * @param from * @throws UnsupportedEncodingException * @throws MessagingException */ public void setFrom(String from) throws UnsupportedEncodingException, MessagingException{ mimeMessage.setFrom(new InternetAddress(username,from)); } /** * 發送郵件<單人發送> * return 是否發送成功 * @throws MessagingException */ public String sendMessage() throws MessagingException{ Transport.send(mimeMessage); return "success"; } /** * 設置附件 * @param file 發送文件的路徑 */ public void setMultipart(String file) throws MessagingException, IOException{ if(multipart==null){ multipart = new MimeMultipart(); } multipart.addBodyPart(writeFiles(file)); mimeMessage.setContent(multipart); } /** * 設置附件<添加多附件> * @param fileList<接收List集合> * @throws MessagingException * @throws IOException */ public void setMultiparts(List<String> fileList) throws MessagingException, IOException{ if(multipart==null){ multipart = new MimeMultipart(); } for(String s:fileList){ multipart.addBodyPart(writeFiles(s)); } mimeMessage.setContent(multipart); } /** * 發送文本內容,設置編碼方式 * <方法與發送附件配套使用> * <發送普通的文本內容請使用setText()方法> * @param s * @param type * @throws MessagingException */ public void setContent(String s,String type) throws MessagingException{ if(multipart==null){ multipart = new MimeMultipart(); } bodypart = new MimeBodyPart(); bodypart.setContent(s, type); multipart.addBodyPart(bodypart); mimeMessage.setContent(multipart); mimeMessage.saveChanges(); } /** * 讀取附件 * @param filePath * @return * @throws IOException * @throws MessagingException */ public BodyPart writeFiles(String filePath)throws IOException, MessagingException{ File file = new File(filePath); if(!file.exists()){ throw new IOException("文件不存在!請確定文件路徑是否正確"); } bodypart = new MimeBodyPart(); DataSource dataSource = new FileDataSource(file); bodypart.setDataHandler(new DataHandler(dataSource)); //文件名要加入編碼,不然出現亂碼 bodypart.setFileName(MimeUtility.encodeText(file.getName())); return bodypart; } /** * 使用SSL登錄 * @throws GeneralSecurityException */ public void openSSL() throws GeneralSecurityException { MailSSLSocketFactory sf =new MailSSLSocketFactory(); sf.setTrustAllHosts(true); pros.put("mail.smtp.ssl.enable", "true"); pros.put("mail.smtp.ssl.socketFactory", sf); } }
ps:代碼來自http://blog.csdn.net/Coding_One/article/details/51354456
4、把代碼copy到位后(記得加你的包名),直接可以使用這個工具類了,下面就貼我寫的demo了
public void sendMailTest() throws IOException, MessagingException { //首先創建一個sendMail對象,它是把發送郵件這件事情封裝成對象,當然需要先告訴它你的用戶名和密碼 SendMail sendMail=new SendMail("你的郵箱地址","你的郵箱密碼"); //這個是告訴它一些配置信息,就像框架的配置文件 Map<String,String> map=new HashMap<String, String>(); map.put("mail.host","smtp.qq.com");//設置郵箱服務器的地址 我這里填的是qq郵箱的,假如你不知道你使用郵箱的服務器地址,百度下就好了,一般都是這樣格式的,比如163就是smtp.163.com map.put("mail.smtp.auth", "true");//開啟驗證,不確認怎么發呢,對吧 sendMail.setPros(map);//然后把你寫好的信息告訴它 //初始化並驗證下你密碼對不對 sendMail.initMessage(); sendMail.setSubject("這里填郵件的標題"); sendMail.setText("這里填正文"); sendMail.setRecipient("這個填你要發給誰"); sendMail.setFrom("這個填你的昵稱,告訴人家你是誰"); //填了一堆亂七八糟的東西,終於可以發送拉 sendMail.sendMessage(); }
這只是一個簡單的demo,更多的群發,添加附件,添加多個附件等等, 工具類里面都有支持
---------------------------------------------一個 我還沒完 的分割線---------------------------------------------
有個重要的事情就是,如果使用qq郵箱,密碼不填你的qq密碼,而是填所謂的授權碼(需要在qq郵箱里面申請,設置-賬戶-開啟SMTP服務)
然后還要開啟ssl ,代碼如下:
//使用ssl登錄 sendMail.openSSL();
這個加哪都可以(除了發送之后。。),最好放在:
然后就可以用循環騷擾你的基友了 嘿嘿嘿
本demo只要加上開啟ssl和使用授權碼就可以使用,非常簡單!
本文禁止一切形式轉載!