- /*
- * 郵件發送類
- */
- public class MailSenderUtil{
- /**
- * 以HTML格式發送郵件,可帶附件,本方法可作爲對外接口提供。
- * @param mailInfo 待發送的郵件信息
- * @throws MessagingException
- * @throws AddressException
- * @throws UnsupportedEncodingException
- */
- public static void sendHtmlMailWithLocalAttach(MailSenderInfo mailInfo) throws AddressException, MessagingException, UnsupportedEncodingException {
- // 判斷是否需要身份認證
- MyAuthenticator authenticator = null;
- // 如果需要身份認證,則創建一個密碼驗證器
- if (mailInfo.isValidate()) {
- authenticator = new MyAuthenticator(mailInfo.getUserName(),mailInfo.getPassword());
- }
- // 根據郵件會話屬性和密碼驗證器構造一個發送郵件的session
- Properties pro = mailInfo.getProperties();
- Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
- // 根據session創建一個郵件消息
- Message mailMessage = new MimeMessage(sendMailSession);
- // 設置發送人
- mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress()));
- // 設置收件人
- String[] toAddress = mailInfo.getToAddress();
- if(toAddress == null || toAddress.length < 1){
- throw new RuntimeException("收件人不得爲空!");
- }
- for (int i = 0; i < toAddress.length; i++) {
- mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress[i]));
- }
- //設置抄送人
- String[] ccAddress = mailInfo.getCcAddress();
- if(ccAddress != null && ccAddress.length > 0){
- for (int i = 0; i < ccAddress.length; i++) {
- mailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(ccAddress[i]));
- }
- }
- // 設置郵件消息的主題
- mailMessage.setSubject(mailInfo.getTitle());
- // 設置郵件消息發送的時間
- mailMessage.setSentDate(new Date());
- // MiniMultipart類是一個容器類,包含MimeBodyPart類型的對象
- Multipart mainPart = new MimeMultipart();
- // 創建一個包含HTML內容的MimeBodyPart
- BodyPart html = new MimeBodyPart();
- // 設置HTML內容
- html.setContent(mailInfo.getContent(), "text/html; charset=GBK");
- mainPart.addBodyPart(html);
- // 添加附件
- addAttachment(mailInfo, mainPart);
- // 將MiniMultipart對象設置爲郵件內容
- mailMessage.setContent(mainPart);
- // 發送郵件
- Transport.send(mailMessage);
- }
- /*
- * 添加郵件附件,用本地的文件作爲附件
- */
- private static void addAttachment(MailSenderInfo mailInfo,Multipart mainPart) throws MessagingException, UnsupportedEncodingException{
- String[] attachFileNames = mailInfo.getAttachFileNames();
- if(attachFileNames != null && attachFileNames.length > 0){
- for (int i = 0; i < attachFileNames.length; i++) {
- MimeBodyPart mdp = new MimeBodyPart();
- // FileDataSource/DataHandler 會用到
- // activation-1.1.jar,jdk6中已經包含了該jar中內容,不再需要單獨下載
- // activation-1.1.jar
- FileDataSource fds = new FileDataSource(attachFileNames[i]);
- DataHandler dh = new DataHandler(fds);
- mdp.setDataHandler(dh);
- // 保持附件名稱與原文件名稱一致的寫法,MimeUtility.encodeText()可以解決中文附件亂碼。
- mdp.setFileName(MimeUtility.encodeText(fds.getName()));
- mainPart.addBodyPart(mdp);
- }
- }
- }
- }
- /**
- * MyAuthenticator bean
- */
- class MyAuthenticator extends Authenticator{
- String userName=null;
- String password=null;
- public MyAuthenticator(){
- }
- public MyAuthenticator(String username, String password) {
- this.userName = username;
- this.password = password;
- }
- protected PasswordAuthentication getPasswordAuthentication(){
- return new PasswordAuthentication(userName, password);
- }
- }
- /**
- * MailSenderInfo bean
- */
- class MailSenderInfo {
- // 發送郵件的服務器的IP和端口
- private String mailServerHost;
- private String mailServerPort;;
- // 郵件發送者的地址
- private String fromAddress;
- //接收人地址
- private String[] toAddress;
- //抄送人地址
- private String[] ccAddress;
- // 登陸郵件發送服務器的用戶名和密碼
- private String userName;
- private String password;
- // 是否需要身份驗證
- private boolean validate = false;
- // 郵件主題
- private String title;
- // 郵件的文本內容
- private String content;
- // 郵件附件的文件名,含磁盤物理路徑,如D:\\Desktop\\index.html
- private String[] attachFileNames;
- /**
- * 獲得郵件會話屬性
- * @return Properties
- */
- public Properties getProperties() {
- Properties p = new Properties();
- p.put("mail.smtp.host", this.mailServerHost);
- p.put("mail.smtp.port", this.mailServerPort);
- p.put("mail.smtp.auth", validate ? "true" : "false");
- return p;
- }
- public String[] getCcAddress() {
- return ccAddress;
- }
- public void setCcAddress(String[] ccAddress) {
- this.ccAddress = ccAddress;
- }
- 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 boolean isValidate() {
- return validate;
- }
- public void setValidate(boolean validate) {
- this.validate = validate;
- }
- public String[] getAttachFileNames() {
- return attachFileNames;
- }
- public void setAttachFileNames(String[] fileNames) {
- this.attachFileNames = fileNames;
- }
- public String getFromAddress() {
- return fromAddress;
- }
- public void setFromAddress(String fromAddress) {
- this.fromAddress = fromAddress;
- }
- 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 getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getTitle() {
- return title;
- }
- public void setTitle(String title) {
- this.title = title;
- }
- public String getContent() {
- return content;
- }
- public void setContent(String textContent) {
- this.content = textContent;
- }
- }
使用
- public static void main(String[] args) throws AddressException, UnsupportedEncodingException, MessagingException {
- MailSenderInfo mail = new MailSenderInfo();
- //設置附件
- mail.setAttachFileNames(new String[]{
- "D:\\Desktop\\首頁.jpg",
- "D:\\Desktop\\測試賬戶.java"
- });
- //設置抄送人
- mail.setCcAddress(new String[]{"[email protected]","[email protected]"});
- //設置正文
- mail.setContent("<h3>http://www.baidu.com</h3>");
- //設置發件郵箱
- mail.setFromAddress("[email protected]");
- //設置發件郵箱密碼
- mail.setPassword("123456");
- //設置郵件服務器
- mail.setMailServerHost("mail.XX.com");
- mail.setMailServerPort("25");
- //設置郵件主題
- mail.setTitle("我是主題");
- //設置收件人
- mail.setToAddress(new String[]{"[email protected]"});
- //設置用戶名
- mail.setUserName("33");
- mail.setValidate(true);
- MailSenderUtil.sendHtmlMailWithLocalAttach(mail);
- }