標籤:java email qq郵箱
1.先建立一個Email所用到的資訊類:
package com.tan.test;import java.util.Properties;/** * 功能:郵箱資訊類 * @author TanZi * @time 2015-4-20上午10:35:47 */public class MailSenderInfo {//發送郵件的伺服器驗證需要的資訊private String mailServerHost; //伺服器的IP地址private String mailServerPort; //連接埠號碼//寄件者的資訊private String formAddress; //寄件者的地址private String userName;// 寄件者的帳號private String password;//寄件者的pndc//接收者private String toAddress;//接收者的地址//發送的主題private String subject;//發送的內容private String content;/** * 功能:獲得郵件會話屬性 * @return */public Properties getProperties(){Properties properties=new Properties();properties.put("mail.smtp.host", this.mailServerHost); //主機地址properties.put("mail.smtp.port", this.mailServerPort); //連接埠號碼properties.put("mail.smtp.auth", "true"); //設定發送授權認證return properties;}//------------------getter/setter-------------------public String getMailServerHost() {return mailServerHost;}public void setMailServerHost(String mailServerHost) {this.mailServerHost = mailServerHost;}public String getMailServerPort() {return mailServerPort;}public void setMailServerPort(String mailServerPort) {this.mailServerPort = mailServerPort;}public String getFormAddress() {return formAddress;}public void setFormAddress(String formAddress) {this.formAddress = formAddress;}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 getToAddress() {return toAddress;}public void setToAddress(String toAddress) {this.toAddress = toAddress;}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;}}
2.建立繼承、重寫認證方法
package com.tan.test;import javax.mail.Authenticator;import javax.mail.PasswordAuthentication;/** * 功能:身分識別驗證類——郵箱帳戶和密碼的驗證 * @author TanZi * @time 2015-4-20上午10:52:17 */public class MyAuthenticator extends Authenticator{String username=null;String password=null;public MyAuthenticator(){}public MyAuthenticator(String username,String passowrd){this.username=username;this.password=passowrd;}/** * 使用者名稱和密碼驗證 */public PasswordAuthentication getPasswordAuthentication(){return new PasswordAuthentication(username, password);}}
3.編寫發email發核心類(怎麼裝載資料。怎麼發送)
package com.tan.test;import java.util.Date;import java.util.Properties;import javax.activation.CommandMap;import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import javax.activation.MailcapCommandMap;import javax.mail.Address;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;/** * 功能:郵件發送的核心類 * @author TanZi * @time 2015-4-20上午11:02:26 */public class SimleMailSender {/** * 功能:郵件發送的核心方法 * @param mailInfo 郵件資訊類 * @return boolean */public boolean sendHtmlMail(MailSenderInfo mailInfo){MyAuthenticator authenticator=new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());//身分識別驗證Properties properties=mailInfo.getProperties(); //根據郵件會話屬性和驗證器構造一個發送郵件的sessionSession sendMailSession=Session.getDefaultInstance(properties, authenticator);try {//定義發送郵件的主體Message mailMessage=new MimeMessage(sendMailSession);//建立寄件者的地址Address fromAddress=new InternetAddress(mailInfo.getFormAddress());//設定郵件訊息的寄件者mailMessage.setFrom(fromAddress);//建立接受者的地址Address toAddress=new InternetAddress(mailInfo.getToAddress());//建立郵件訊息的接受者mailMessage.setRecipient(Message.RecipientType.TO, toAddress);//BCC:密送..CC:抄送.. TO:直接發送//郵件的主題mailMessage.setSubject(mailInfo.getSubject());//設定郵件發送的時間mailMessage.setSentDate(new Date());//設定郵件訊息的主要內容//String mailContent=mailInfo.getContent();//建立一個容器Multipart maimPart=new MimeMultipart();//建立一個包含html內容的MimeBodyPartBodyPart html=new MimeBodyPart();//設定html的郵件內容html.setContent(mailInfo.getContent(),"text/html;charset=utf-8");maimPart.addBodyPart(html);//建立附件BodyPart attach=new MimeBodyPart();DataSource source=new FileDataSource("E:\\Code\\Movie\\images\\four.jpg");//載入要作為附件的檔案attach.setDataHandler(new DataHandler(source));attach.setFileName("four.jpg");maimPart.addBodyPart(attach);//設定內容mailMessage.setContent(maimPart);//設定 發送html格式的郵件標頭資訊MailcapCommandMap mc=(MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); CommandMap.setDefaultCommandMap(mc); //傳送檔案 Transport.send(mailMessage); return true;} catch (AddressException e) {e.printStackTrace();} catch (MessagingException e) {// TODO Auto-generated catch blocke.printStackTrace();} return false;}}4。測試類別
package com.tan.test;/** * 功能: * @author TanZi * @time 2015-4-20下午1:16:15 */public class TestMail {/** * 功能: * @param args */public static void main(String[] args) {MailSenderInfo mailInfo = new MailSenderInfo();System.out.println("");mailInfo.setMailServerHost("smtp.qq.com"); // 郵件伺服器主機mailInfo.setMailServerPort("25"); // 伺服器連接埠 SMTP:單單的郵件傳輸協議 連接埠:25mailInfo.setUserName("571868789"); // 寄件者使用者名稱mailInfo.setPassword("tanliu1234"); // 寄件者密碼mailInfo.setFormAddress("[email protected]"); //寄件者地址//mailInfo.setToAddress("[email protected]"); // 接收者地址String toAddress = "[email protected]";mailInfo.setToAddress(toAddress);String subject = "TanZi-------text"; // 主題String content = "<a href='http://blog.csdn.net/u011707402' >"; content += "<div style='width:650px;background-color:#DBDBFF;"; content += "text-align:center;color:red;font-size:20px;border:0 solid red;'>"; content +="<b>恭喜你收到我的資訊<br />"; content +="<a href='http://blog.csdn.net/u011707402'>罈子成長記學習知識</a><br />"; content +="罈子"; content +="</b><img width='100%' src='http://www.nipic.com/show/7364191.html' /></div></a>";mailInfo.setSubject(subject);mailInfo.setContent(content);SimleMailSender sms = new SimleMailSender();boolean flag = sms.sendHtmlMail(mailInfo); // 發送郵件if(flag){System.out.println("成功!");}else{System.out.println("失敗!");}}}
5.注意事項
- 發送郵件錯誤 454 Authentication failed, please open smtp flag first! ----(方法)在QQ郵箱的設定裡面,找到賬戶-》POP3/IMAP/SMTP選擇開啟POP3/SMTP服務
- 535 Authentication failed(原因):帳號和密碼錯誤
關於java發送email案例