1、什么是java mail
JAVA MAIL是利用現有的郵件賬戶發送郵件的工具,通過JAVA Mail的操控,讓程序自動的使用設置的郵箱發送郵件。
這一機制被廣泛的用在注冊激活和垃圾郵件的發送等方面。
2、郵件發送的大致過程
1、構建一個繼承自javax.mail.Authenticator的具體類,並重寫里面的getPasswordAuthentication()方法。
此類是用作登錄校驗的,以確保你對該郵箱有發送郵件的權利。
2、構建一個properties文件,該文件中存放SMTP服務器地址等參數。
3、通過構建的properties文件和javax.mail.Authenticator具體類來創建一個javax.mail.Session。
Session的創建,就相當於登錄郵箱一樣。剩下的自然就是新建郵件。
4、構建郵件內容,一般是javax.mail.internet.MimeMessage對象,並指定發送人,收信人,主題,內容等等。
5、使用javax.mail.Transport工具類發送郵件。
3、准備工作
下載JavaMail jar包,導入工程。
http://www.oracle.com/technetwork/java/javamail/index-138643.html
4、案例代碼
MyEmailAutherticator.java
import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class MyEmailAutherticator extends Authenticator { //用戶名(登錄郵箱) private String username; //密碼 private String password; public MyEmailAutherticator() { super(); } //初始化郵箱和密碼 public MyEmailAutherticator(String username, String password) { this.username = username; this.password = password; } //用作登錄校驗,以確保對該郵箱有發送郵件的權利 public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } //set and get method 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; } }
Mail.java
import java.util.Date; import java.util.Properties; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.SendFailedException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class Mail { //發送郵件的帳號和密碼 private String username="abc123456@qq.com"; private String password="xxxxxx"; private String host = "smtp.qq.com"; private String mail_head_name = "this is head of this mail"; private String mail_head_value = "this is head of this mail"; private String mail_to = "123456789@qq.com"; private String mail_from = "abc123456@qq.com"; private String mail_subject = "this is the subject of this test mail"; private String mail_body = "this is mail_body of this test mail"; private String personalName = "我的郵件"; public void sendMail() throws SendFailedException{ try { //發送郵件的props文件 Properties props = new Properties(); // 初始化props props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); System.out.println(props); //進行郵件服務用戶認證 Authenticator auth = new MyEmailAutherticator(username,password); // 創建session,和郵件服務器進行通訊 Session session = Session.getDefaultInstance(props,auth); // 創建mime類型郵件 MimeMessage message = new MimeMessage(session); //設置郵件格式 message.setContent("Hello","text/html;charset=utf-8"); // 設置主題 message.setSubject(mail_subject); //設置郵件內容 message.setText(mail_body); //設置郵件標題 message.setHeader(mail_head_name, mail_head_value); message.setSentDate(new Date());//設置郵件發送時期 Address address = new InternetAddress(mail_from,personalName); //設置郵件發送者的地址 message.setFrom(address); //======單發郵件====== //設置郵件接收者的地址 Address toaddress = new InternetAddress(mail_to); // 設置收件人 message.addRecipient(Message.RecipientType.TO,toaddress); //======群發郵件====== // List<String> recipients = new ArrayList<String>(); // recipients.add("123456789@qq.com"); // recipients.add("234567890@gmail.com"); // final int num = recipients.size(); // InternetAddress[] addresses = new InternetAddress[num]; // for (int i = 0; i < num; i++) { // addresses[i] = new InternetAddress(recipients.get(i)); // } // message.setRecipients(Message.RecipientType.TO, addresses); System.out.println(message); // 發送郵件 Transport.send(message); System.out.println("Send Mail Ok!"); } catch (Exception e) { e.printStackTrace(); } } }
Test.java
public class Test { public static void main(String[] args) { Mail m = new Mail(); try { m.sendMail(); } catch (Exception e) { } } }
2015-8-6補充代碼
public class Demo1 { @Test public void fun1() throws Exception { /* * 1. 得到session */ Properties props = new Properties(); props.setProperty("mail.host", "smtp.163.com"); props.setProperty("mail.smtp.auth", "true"); Authenticator auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("itcast_cxf", "itcast"); } }; Session session = Session.getInstance(props, auth); /* * 2. 創建MimeMessage */ MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("itcast_cxf@163.com"));//設置發件人 msg.setRecipients(RecipientType.TO, "itcast_cxf@126.com");//設置收件人 msg.setRecipients(RecipientType.CC, "itcast_cxf@sohu.com");//設置抄送 msg.setRecipients(RecipientType.BCC, "itcast_cxf@sina.com");//設置暗送 msg.setSubject("這是來自ITCAST的測試郵件"); msg.setContent("這就是一封垃圾郵件!", "text/html;charset=utf-8"); /* * 3. 發 */ Transport.send(msg); } /** * 帶有附件的郵件!!! */ @Test public void fun2() throws Exception { /* * 1. 得到session */ Properties props = new Properties(); props.setProperty("mail.host", "smtp.163.com"); props.setProperty("mail.smtp.auth", "true"); Authenticator auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("itcast_cxf", "itcast"); } }; Session session = Session.getInstance(props, auth); /* * 2. 創建MimeMessage */ MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("itcast_cxf@163.com"));//設置發件人 msg.setRecipients(RecipientType.TO, "itcast_cxf@126.com");//設置收件人 msg.setSubject("這是來自ITCAST的測試郵件有附件"); //////////////////////////////////////////////////////// /* * 當發送包含附件的郵件時,郵件體就為多部件形式! * 1. 創建一個多部件的部件內容!MimeMultipart * MimeMultipart就是一個集合,用來裝載多個主體部件! * 2. 我們需要創建兩個主體部件,一個是文本內容的,另一個是附件的。 * 主體部件叫MimeBodyPart * 3. 把MimeMultipart設置給MimeMessage的內容! */ MimeMultipart list = new MimeMultipart();//創建多部分內容 // 創建MimeBodyPart MimeBodyPart part1 = new MimeBodyPart(); // 設置主體部件的內容 part1.setContent("這是一封包含附件的垃圾郵件", "text/html;charset=utf-8"); // 把主體部件添加到集合中 list.addBodyPart(part1); // 創建MimeBodyPart MimeBodyPart part2 = new MimeBodyPart(); part2.attachFile(new File("F:/f/白冰.jpg"));//設置附件的內容 part2.setFileName(MimeUtility.encodeText("大美女.jpg"));//設置顯示的文件名稱,其中encodeText用來處理中文亂碼問題 list.addBodyPart(part2); msg.setContent(list);//把它設置給郵件作為郵件的內容。 //////////////////////////////////////////////////////// /* * 3. 發 */ Transport.send(msg); } }