<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    道非道 非常道

    勤思、謹言、慎行、厚積、薄發

    統計

    web

    天圓

    經濟 政治 軍事

    鍵康

    spring3 email 發送代碼

    使用spring3來進行java 郵件的發送。閑話不說,直接上代碼。
    配置代碼都超過了主代碼 
    不過配置代碼都是常用的,留著備份吧。
    mavne pox 配置



     1 <dependency>
     2             <groupId>javax.mail</groupId>
     3             <artifactId>mail</artifactId>
     4             <version>1.4</version>
     5         </dependency>
     6     <dependency>
     7             <groupId>org.springframework</groupId>
     8             <artifactId>spring-beans</artifactId>
     9             <version>${org.springframework.version}</version>
    10         </dependency>

    spring-xml 配置
    <bean id="propertyConfigurer"
            class
    ="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>classpath:cfg/config.properties</value>
                </list>
            </property>
        </bean>

        <bean id="mail"
            class
    ="org.springframework.mail.javamail.JavaMailSenderImpl">
            <!-- SMTP發送郵件的服務器的IP和端口 -->
            <property name="host" value="${mail.host}" />
            <property name="port" value="${mail.port}" />

            <!-- 登陸SMTP郵件發送服務器的用戶名和密碼 -->
            <property name="username" value="${mail.username}" />
            <property name="password" value="${mail.password}" />

            <!-- 獲得郵件會話屬性,驗證登錄郵件服務器是否成功-->
            <property name="javaMailProperties">
                <props>
                    <prop key="mail.smtp.auth">true</prop>
                    <prop key="prop">true</prop>
                    <prop key="mail.smtp.timeout">25000</prop>
                </props>
            </property>
        </bean>


    properties 文件配置

    mail.host=smtp.yeah.net
    mail.port=25
    mail.username=****
    mail.password=****
    java 類分別為:

    import org.springframework.context.support.AbstractApplicationContext;

    import com.ms.AppContext;

    public class SpringHelper {

        /**
         * 獲取spring依賴注入的對象
         * 
         * 
    @param name
         * 
    @return Object Bean
         
    */
        public static Object getBean(String name) {
            AbstractApplicationContext ctx = AppContext.getInstance()
                    .getAppContext();

            return ctx.getBean(name);
        }
    }


    import java.util.ArrayList;
    import java.util.List;

    import org.springframework.context.support.AbstractApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    public class AppContext {
        private static AppContext instance;

        private volatile AbstractApplicationContext appContext;

        public synchronized static AppContext getInstance() {
            if (instance == null) {
                instance = new AppContext();
            }

            return instance;
        }

        private AppContext() {
            List<String> list = new ArrayList<String>();
            list.add("/cfg/*.xml");

            String ss[] = list.toArray(new String[] {});
            for (int i = 0; i < ss.length; i++) {
                System.out.println("ss[" + i + "]" + ss[i]);

            }

            this.appContext = new ClassPathXmlApplicationContext(ss);
        }

        public AbstractApplicationContext getAppContext() {
            return appContext;
        }
    }



    import java.io.File;
    import java.util.Date;

    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeUtility;

    import org.apache.log4j.Logger;
    import org.apache.log4j.PropertyConfigurator;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.MimeMessageHelper;

    import com.ms.SpringHelper;
    import com.util.Configuration;

    /**
     * 發送郵件 工具
     * 
     * 
    @author 
     * @file com.ms.util --- SentMaileUtil.java
     * 
    @version 2013-2-28 -下午03:42:03
     
    */
    public class SendMaileUtil {
        private static JavaMailSender javaMailSender;

        private static Logger logger = Logger.getLogger(SendMaileUtil.class);

        private static JavaMailSender newIntstance() {
            if (javaMailSender == null) {
                javaMailSender = (JavaMailSender) SpringHelper.getBean("mail");
            }
            return javaMailSender;
        }

        /**
         * 發送的文本測試郵件
         * 
         * 
    @param to
         * 
    @param mailSubject
         * 
    @param mailBody
         
    */
        public static void sendTextMaile(String to, String mailSubject,
                String mailBody) {
            if (logger.isDebugEnabled())
                logger.debug("準備發送文本形式的郵件");
            SimpleMailMessage mail1 = new SimpleMailMessage();
            String from = Configuration.getValue("mail.form");
            mail1.setFrom(from);// 發送人名片
            mail1.setTo(to);// 收件人郵箱
            mail1.setSubject(mailSubject);// 郵件主題
            mail1.setSentDate(new Date());// 郵件發送時間
            mail1.setText(mailBody);

            // 群發
            SimpleMailMessage[] mailMessages = { mail1 };
            newIntstance().send(mailMessages);

            if (logger.isDebugEnabled())
                logger.debug("文本形式的郵件發送成功!!!");
        }

        /**
         * 以 HTML腳本形式郵件發送
         * 
         * 
    @param to
         * 
    @param mailSubject
         * 
    @param mailBody
         
    */
        public static void sendHtmlMail(String to, String mailSubject,
                String mailBody) {
            JavaMailSender mailSender = newIntstance();
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            try {
                if (logger.isDebugEnabled())
                    logger.debug("HTML腳本形式郵件正在發送");
                // 設置utf-8或GBK編碼,否則郵件會有亂碼
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true,
                        "UTF-8");
                // 設置發送人名片
                String from = Configuration.getValue("mail.form");
                helper.setFrom(from);
                // 設置收件人名片和地址
                helper.setTo(new InternetAddress("\""
                        + MimeUtility.encodeText("gamil郵箱") + "\" <" + to + ">"));// 發送者
                // 郵件發送時間
                helper.setSentDate(new Date());
                // 設置回復地址
                helper.setReplyTo(new InternetAddress(from));
                // 設置抄送的名片和地址
                
    // helper.setCc(InternetAddress.parse(MimeUtility.encodeText("抄送人001")
                
    // + " <@163.com>," + MimeUtility.encodeText("抄送人002")
                
    // + " <@foxmail.com>"));
                
    // 主題
                helper.setSubject("????");
                // 郵件內容,注意加參數true,表示啟用html格式
                helper
                        .setText(
                                "<html><head></head><body><h1>hello!!我是喬布斯</h1></body></html>",
                                true);
                // 發送
                mailSender.send(mimeMessage);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (logger.isDebugEnabled())
                logger.debug("HTML腳本形式郵件發送成功!!!");
        }

        /**
         * 以附件的形式發送郵件
         * 
         * 
    @param to
         *            收件人eamil 地址
         * 
    @param toName
         *            收件人昵稱
         * 
    @param mailSubject
         *            主題
         * 
    @param mailBody
         *            內容體
         * 
    @param files
         *            附件
         
    */
        public static void sendFileMail(String to, String toName,
                String mailSubject, String mailBody, File[] files) {
            JavaMailSender mailSender = newIntstance();
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            try {
                if (logger.isDebugEnabled())
                    logger.debug("帶附件和圖片的郵件正在發送");

                // 設置utf-8或GBK編碼,否則郵件會有亂碼
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true,
                        "UTF-8");
                // 設置發送人名片
                String from = Configuration.getValue("mail.form");
                helper.setFrom(from);

                // 設置收件人郵箱
                helper.setTo(new InternetAddress("\""
                        + MimeUtility.encodeText(toName) + "\" <" + to + ">"));

                // 設置回復地址
                
    // helper.setReplyTo(new InternetAddress("@qq.com"));

                
    // 設置收件人抄送的名片和地址(相當于群發了)
                
    // helper.setCc(InternetAddress.parse(MimeUtility.encodeText("郵箱001")
                
    // + " <@163.com>," + MimeUtility.encodeText("郵箱002")
                
    // + " <@foxmail.com>"));

                
    // 主題
                helper.setSubject(mailSubject);
                // 郵件內容,注意加參數true,表示啟用html格式
                helper.setText(mailBody);
                if (files != null && files.length > 0) {
                    for (int i = 0; i < files.length; i++)
                        // 加入附件
                        helper.addAttachment(MimeUtility.encodeText(files[i]
                                .getName()), files[i]);
                }
                // 加入插圖
                helper.addInline(MimeUtility.encodeText("pic01"), new File(
                        "c:/temp/2dd24be463.jpg"));
                // 發送
                mailSender.send(mimeMessage);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (logger.isDebugEnabled()) {
                logger.debug("帶附件和圖片的郵件發送成功!!!");
            }
        }

        public static void main(String[] args) {
            PropertyConfigurator.configure(ClassLoader
                    .getSystemResource("cfg/log4j.properties"));

            SendMaileUtil.sendTextMaile("*****@gmail.com",
                    "Spring Mail 測試郵件", "Hello,Boy,This is my Spring Mail,哈哈!!");

            SendMaileUtil.sendHtmlMail("*****@gmail.com", nullnull);
            File file = new File("c:/temp");
            File[] fs = file.listFiles();

            SendMaileUtil.sendFileMail("******@yeah.net", "昵稱", "主題", "內容",
                    fs);

        }
    }









    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;

    import com.pub.Forward;

    /**
     * 讀取properties文件
     * 
    @author 
     *
     
    */
    public class Configuration
    {
        private static Properties propertie;
        private InputStream in;
        private static Configuration config = new Configuration();
        
        /**
         * 初始化Configuration類
         
    */
        public Configuration()
        {
            propertie = new Properties();
            try {
    //            System.out.println(System.getProperty("user.dir"));
    //            inputFile = new FileInputStream("cfg/config.properties");
                in =  ClassLoader.getSystemResourceAsStream("cfg/config.properties");
                propertie.load(in);
                in.close();
            } catch (FileNotFoundException ex) {
                System.out.println("讀取屬性文件--->失敗!- 原因:文件路徑錯誤或者文件不存在");
                ex.printStackTrace();
            } catch (IOException ex) {
                System.out.println("裝載文件--->失敗!");
                ex.printStackTrace();
            }        
        }
        

        
        /**
         * 重載函數,得到key的值
         * 
    @param key 取得其值的鍵
         * 
    @return key的值
         
    */
        public static  String getValue(String key)
        {
            if(propertie.containsKey(key)){
                String value = propertie.getProperty(key);//得到某一屬性的值
                return value;
            }
            else 
                return "";
        }//end getValue()

        


        
        public static void main(String[] args)
        {

            System.out.println(Configuration.getValue("aaa"));
            System.out.println(System.getProperty("user.dir"));


            
        }//end main()
        
    }//end class ReadConfigInfo



























    posted on 2013-02-28 18:08 星期五 閱讀(2444) 評論(2)  編輯  收藏 所屬分類: JAVA EEJAVA SE

    評論

    # re: spring3 email 發送代碼 2014-09-14 04:07 fffb

    565  回復  更多評論   

    # re: spring3 email 發送代碼 2016-08-02 11:36 hr

    test  回復  更多評論   


    只有注冊用戶登錄后才能發表評論。


    網站導航:
     
    主站蜘蛛池模板: 四虎影视永久免费视频观看| 亚洲中文无码永久免费| 亚洲国产一区二区视频网站| 亚洲欧洲日产国码久在线| 性xxxx视频播放免费| 亚洲Av永久无码精品黑人| 免费看大黄高清网站视频在线| 亚洲国产精品日韩av不卡在线| 日韩高清在线高清免费| 曰批免费视频播放免费| 亚洲午夜久久久久久噜噜噜| 可以免费观看的毛片| 亚洲综合久久成人69| 性盈盈影院免费视频观看在线一区| 亚洲精品理论电影在线观看| 国产乱子影视频上线免费观看| 最新亚洲人成网站在线观看| 亚洲日韩精品无码专区网站| 久久国产精品国产自线拍免费| 久久久久亚洲精品日久生情| 国产精品视频免费一区二区| 国产成人不卡亚洲精品91| 亚洲精品中文字幕乱码三区| 久草免费在线观看视频| 无码色偷偷亚洲国内自拍| 中文字幕精品亚洲无线码二区| 亚洲一区二区三区免费在线观看| 日韩国产欧美亚洲v片| 亚洲综合无码AV一区二区| 亚洲一区二区免费视频| 无码色偷偷亚洲国内自拍| 婷婷久久久亚洲欧洲日产国码AV| 成年免费大片黄在线观看岛国 | 亚洲综合色丁香麻豆| 成年人免费网站在线观看| 在线播放国产不卡免费视频| 亚洲综合自拍成人| 亚洲av日韩av欧v在线天堂| 84pao强力永久免费高清| 日日摸日日碰夜夜爽亚洲| 亚洲高清在线mv|