道非道 非常道

勤思、谨言、慎行、厚积、薄发

统计

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 星期五 阅读(2439) 评论(2)  编辑  收藏 所属分类: JAVA EEJAVA SE

评论

# re: spring3 email 发送代码 2014-09-14 04:07 fffb

565  回复  更多评论   

# re: spring3 email 发送代码 2016-08-02 11:36 hr

test  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: