1. 程式人生 > >郵件推送 Java代碼

郵件推送 Java代碼

cati pass protected esc 郵件 .text extend *** pwd

package mail;


/** 
 * @Description:郵件信息類 
 *  
 * @ClassName: SimpleMail 
 */ 
public class Mail {
        /** 
         * 主題 
         */  
        private String subject;  
        /** 
         * 內容 
         */  
        private String content;  
      
        /** 
         * @return the subject 
         
*/ public String getSubject() { return subject; } /** * @param subject * the subject to set */ public void setSubject(String subject) { this.subject = subject; } /** * @return the content
*/ public String getContent() { return content; } /** * @param content * the content to set */ public void setContent(String content) { this.content = content; } }
package mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/** * @Description: 郵箱登錄類 * * @ClassName: MailAuthenticator */ public class MailAuthenticator extends Authenticator { /** * 用戶名(登錄郵箱) */ private String username; /** * 密碼 */ private String password; /** * @return the username */ public String getUsername() { return username; } /** * @param username the username to set */ public void setUsername(String username) { this.username = username; } /** * @return the password */ public String getPassword() { return password; } /** * @param password the password to set */ public void setPassword(String password) { this.password = password; } /** * @param username * @param password */ public MailAuthenticator(String username, String password) { this.username = username; this.password = password; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }
package mail;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/** 
 * @Description: 郵件發送常量類 
 * 
 * @ClassName: MailConstant  
 */ 
public class MailConstant {
    
    public static final String MAIL_USER = "*******";  //公共郵箱 
    public static final String MAIL_PWD = "*******";  //公共郵箱密碼
    public static final boolean MAIL_IFDEBUG = true;  
    public static final String MAIL_CONTENT_CHARSET = "text/html;charset=utf-8";   
    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH時mm分ss秒 E");  
    public static final String MAIL_TITLE = "****8" + sdf.format(new Date());//郵件標題  
    public static Object getMailContent(List<MessageEntity> list){  
        StringBuffer sb = new StringBuffer();  
        sb.append("<div style=‘width:1024px;height:auto;margin:0px auto;background-color:#66CCFF;font-size:14px;font-family:微軟雅黑;border-radius:5px;padding:5px;‘><center><h1>");  
        sb.append("</h1></center><div style=‘margin-left:20px;margin-bottom:10px;‘><b>郵件標題</b><br/><br/>"); 
        sb.append("<table border=‘1‘>");
        for(int i=0;i<list.size();i++){
        sb.append("<tr>"
                + "<td>"
                + list.get(i).getName()
                + "</td>"
                + "<td>"
                + list.get(i).getpName()
                + "</td>"
                + "<td>"
                + list.get(i).getAge()
                + "</td>"
                + "<td>"
                + list.get(i).getAddress()
                + "</td>"
                + "</tr>");
        }
        sb.append("</table>");
        sb.append("</div></div>");
        return sb.toString();  
    }  

}
package mail;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/** 
 * @Description:郵件發送類 
 *  
 */ 
public class MailSender {

     
    /** 
     * 發送郵件的props文件 
     */  
    private final transient Properties props = new Properties();  
    /** 
     * 郵件服務器登錄驗證 
     */  
    private transient MailAuthenticator authenticator;  
  
    /** 
     * 郵箱session 
     */  
    private transient Session session;  
  
    
    public MailSender(){
        
    }
    /** 
     * 初始化郵件發送器 
     *  
     * @param smtpHostName 
     *            SMTP郵件服務器地址 
     * @param username 
     *            發送郵件的用戶名(地址) 
     * @param password 
     *            發送郵件的密碼 
     */  
    public MailSender(final String smtpHostName, final String username,  
            final String password) {  
        init(username, password, smtpHostName);  
    }  
  
    /** 
     * 初始化郵件發送器 
     *  
     * @param username 
     *            發送郵件的用戶名(地址),並以此解析SMTP服務器地址 
     * @param password 
     *            發送郵件的密碼 
     */  
    public MailSender(final String username, final String password) {  
        // 通過郵箱地址解析出smtp服務器,對大多數郵箱都管用  
        final String smtpHostName = "smtp." + username.split("@")[1];  
        init(username, password, smtpHostName);  
  
    }  
  
    /** 
     * @Description: 初始化 
     *  
     * @param username 
     *            發送郵件的用戶名(地址) 
     * @param password 
     *            密碼 
     * @param smtpHostName 
     *            SMTP主機地址 
     *  
     */  
    private void init(String username, String password, String smtpHostName) {  
        // 初始化props  
        props.put("mail.smtp.host", smtpHostName);  
        props.put("mail.smtp.auth", "true");  
        // 驗證  
        authenticator = new MailAuthenticator(username, password);  
        // 創建session  
        session = Session.getInstance(props, authenticator);  
        // 打印一些調試信息  
        session.setDebug(MailConstant.MAIL_IFDEBUG);  
    }  
  
    /** 
     * @Description: 發送郵件 
     *  
     * @param recipient 
     *            收件人郵箱地址 
     * @param subject 
     *            郵件主題 
     * @param content 
     *            郵件內容 
     * @throws AddressException 
     * @throws MessagingException 
     *  
     * @Title: MailSender.java  
     */  
    public void send(String recipient, String subject, Object content) throws Exception {  
        send(recipient, subject, content, null);  
    }  
  
    /** 
     * 發送郵件 
     *  
     * @param recipient 
     *            收件人郵箱地址 
     * @param subject 
     *            郵件主題 
     * @param content 
     *            郵件內容 
     * @param files 
     *            附件 
     * @throws Exception 
     */  
    public void send(String recipient, String subject, Object content, Vector<File> files) throws Exception {  
        // 創建mime類型郵件  
        final MimeMessage message = new MimeMessage(session);  
        // 設置發信人  
        message.setFrom(new InternetAddress(authenticator.getUsername(),"*****郵件標題****","UTF-8"));  
        // 設置收件人  
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(  
                recipient));  
        // 設置主題  
        message.setSubject(subject);  
        // 設置郵件內容  
        if (null == files || files.size() == 0) {  
            message.setContent(content.toString(), MailConstant.MAIL_CONTENT_CHARSET);  
        } else {  
            //創建 Mimemultipart添加內容(可包含多個附件)  
            MimeMultipart multipart = new MimeMultipart();  
            //MimeBodyPart(用於信件內容/附件)  
            BodyPart bodyPart = new MimeBodyPart();  
            bodyPart.setContent(content.toString(), MailConstant.MAIL_CONTENT_CHARSET);  
            //添加到MimeMultipart對象中  
            multipart.addBodyPart(bodyPart);  
            for (int i = 0; i < files.size(); i++) {  
                File file = (File) files.elementAt(i);  
                String fname = file.getName();  
                //創建FileDAtaSource(用於添加附件)  
                FileDataSource fds = new FileDataSource(file);  
                BodyPart fileBodyPart = new MimeBodyPart();  
                // 字符流形式裝入文件  
                fileBodyPart.setDataHandler(new DataHandler(fds));  
                // 設置附件文件名  
                fileBodyPart.setFileName(fname);  
                multipart.addBodyPart(fileBodyPart);  
                message.setContent(multipart);  
            }  
        }  
        // 設置發信時間  
        message.setSentDate(new Date());  
        // 存儲郵件信息  
        message.saveChanges();  
//      message.setFileName(filename)  
        // 發送郵件  
        Transport.send(message);  
    }  
  
    /** 
     * @Description: 群發郵件 
     *  
     * @param recipients 
     *            收件人們 
     * @param subject 
     *            主題 
     * @param content 
     *            內容 
     * @throws AddressException 
     * @throws MessagingException 
     */  
    public void send(List<String> recipients, String subject, Object content) throws Exception {  
        send(recipients, subject, content, null);  
    }  
  
    /** 
     * 群發郵件 
     *  
     * @param recipients 
     *            收件人們 
     * @param subject 
     *            主題 
     * @param content 
     *            內容 
     * @param files 
     *            附件 
     * @throws Exception 
     */  
    public void send(List<String> recipients, String subject, Object content, Vector<File> files) throws Exception {  
        // 創建mime類型郵件  
        final MimeMessage message = new MimeMessage(session);  
        // 設置發信人  
        message.setFrom(new InternetAddress(authenticator.getUsername()));  
        // 設置收件人們  
        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);  
        // 設置主題  
        message.setSubject(subject);  
        // 設置郵件內容  
        if (null == files || files.size() == 0) {  
            message.setContent(content.toString(), MailConstant.MAIL_CONTENT_CHARSET);  
        } else {  
             //創建 Mimemultipart添加內容(可包含多個附件)  
            MimeMultipart multipart = new MimeMultipart();  
              //MimeBodyPart(用於信件內容/附件)  
            BodyPart bodyPart = new MimeBodyPart();  
            bodyPart.setContent(content.toString(), MailConstant.MAIL_CONTENT_CHARSET);  
             //添加到MimeMultipart對象中  
            multipart.addBodyPart(bodyPart);  
            for (int i = 0; i < files.size(); i++) {  
                File file = (File) files.elementAt(i);  
                String fname = file.getName();  
                //創建FileDAtaSource(用於添加附件)  
                FileDataSource fds = new FileDataSource(file);  
                BodyPart fileBodyPart = new MimeBodyPart();  
                // 字符流形式裝入文件  
                fileBodyPart.setDataHandler(new DataHandler(fds));  
                // 設置附件文件名  
                fname = new String(fname.getBytes("UTF-8"), "ISO-8859-1");  
                fileBodyPart.setFileName(fname);  
                multipart.addBodyPart(fileBodyPart);  
                message.setContent(multipart);  
            }  
        }  
        // 設置發信時間  
        message.setSentDate(new Date());  
        // 存儲郵件信息  
        message.saveChanges();  
        // 發送郵件  
        Transport.send(message);  
    }  
  
    /** 
     * @Description: 發送郵件 
     *  
     * @param recipient 
     *            收件人郵箱地址 
     * @param mail 
     *            郵件對象 
     * @throws Exception 
     *  
     * @Title: MailSender.java 
     */  
    public void send(String recipient, Mail mail) throws Exception {  
        send(recipient, mail.getSubject(), mail.getContent());  
    }  
  
    /** 
     * @Description: 群發郵件 
     *  
     * @param recipients 
     *            收件人們 
     * @param mail 
     *            郵件對象 
     * @throws Exception 
     *  
     * @Title: MailSender.java 
     */  
    public void send(List<String> recipients, Mail mail) throws Exception {  
        send(recipients, mail.getSubject(), mail.getContent());  
    }  
  
    /** 
     * 群發郵件 
     *  
     * @param recipients 
     *            收件人們 
     * @param mail 
     *            郵件對象 
     * @param files 
     *            附件 
     * @throws Exception  
     */  
    public void send(List<String> recipients, Mail mail, Vector<File> files) throws Exception {  
        send(recipients, mail.getSubject(), mail.getContent(), files);  
    }  
    
}
package mail;

/** 
 * @Description: 隨機碼工具類 
 *  
 * @ClassName: RandomCodeUtil 
 * @Copyright: Copyright (c) 2014 
 *  
 * @author Comsys-LZP 
 * @date 2014-5-28 上午11:07:34 
 * @version V2.0 
 */  
public class RandomCodeUtil {
    
    /** 
     * 隨機碼集合 
     */  
    private static final String[] randCode = { "0", "1", "2", "3", "4", "5", "6",  
            "7", "8", "9", "q", "w", "e", "r", "t", "y", "u", "i", "o", "p",  
            "a", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v",  
            "b", "n", "m" };  
      
    /** 
     * @Description: 產生指定長度的隨機碼 
     * 
     * @param codeLength 
     * @return 
     * 
     * @Title: RandomCodeUtil.java 
     */  
    public static String randomCode(Integer codeLength) throws Exception {  
        try {  
            StringBuffer code = new StringBuffer();  
            if(null == codeLength || 0 == codeLength){  
                codeLength = 4;  
            }  
            for (int i = 0; i < codeLength; i++) {  
                code.append(randCode[(int)Math.floor(Math.random() * 36)]);  
            }  
            return code.toString();  
        } catch (Exception e) {  
            throw new RuntimeException("Random Code Error");  
        }  
    }  
      
    /** 
     * @Description: 生成長度為4的隨機碼 
     * 
     * @return 
     * @throws Exception 
     * 
     * @Title: RandomCodeUtil.java 
     * @Copyright: Copyright (c) 2014 
     * 
     * @author Comsys-LZP 
     * @date 2014-5-28 下午01:19:33 
     * @version V2.0 
     */  
    public static String randomCode() throws Exception{  
        return randomCode(null);  
    }  

}

郵件推送 Java代碼