spring 发送邮件

springframework 发送邮件

邮件功能对于web应用的重要性是不言而喻的,那么如何实现就成了一个不小的问题,还好spring为我们解决了这个问题,下面就是具体的实现:

首先导入一下两个包

org.springframework:spring-context-support:4.3.1.RELEASE
javax.mail:mail:1.4.6

其次创建 mail-config.properties 文件

mail.host = smtp.xxxxx.com
mail.username = xxxxxxx
mail.password = xxxxxx
mail.port = 25

**之后就是配置 applicationContext.xml **:

(1) 在xml中引入mail-config.properties:

 <bean id="configurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath*:mail-config.properties</value>
            </list>
        </property>
    </bean>

(2) 配置mail:

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.host}"/>
        <property name="username" value="${mail.username}"/>
        <property name="password" value="${mail.password}"/>
        <property name="port" value="${mail.port}"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.timeout">25000</prop>
                <prop key="mail.debug">true</prop>
            </props>
        </property>
    </bean>

**下面就是具体的实现了 **:

@Service
public class MailService {
    @Resource
    private MailSender mailSender;

    public void sendMessage(String[] to,String subject,String text){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(text);

        mailSender.send(simpleMailMessage);
    }
}

好了,大功告成!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值