使用spring的JavaMailSender发送邮件

JavaMailSender在spring-context-support.jar中
代码结构如下:

使用spring的JavaMailSender发送邮件_第1张图片

1、pom.xml中加入以下依赖:

<dependency>
         <groupId>org.springframeworkgroupId>
         <artifactId>spring-context-supportartifactId>
         <version>4.2.6.RELEASEversion>
    dependency>
    <dependency>
         <groupId>javax.mailgroupId>
         <artifactId>mailartifactId>
         <version>1.4.7version>
    dependency>

2、applicationContext.xml配置如下:



<beans>
   <bean id="configurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
         <list>
            <value>/mail.propertiesvalue>
         list>
      property>
   bean>
   <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
   <bean id="MailSenderDemo" class="com.mail.MailSenderDemo">
   bean>
beans>

3、mail.properties如下:

mail.host=mail.ustcinfo.com
mail.username=gu.erlei@ustcinfo.com
mail.password=******

主要是邮箱服务器、个人邮箱用户名和密码

4、spring-mail.xml如下:



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

5.MailSenderDemo.java如下:

package com.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

public class MailSenderDemo {
    @Autowired
    private JavaMailSender mailSender;
    public void send(SimpleMailMessage mail){
     mailSender.send(mail);
    }
}

6、测试类SendTest.java如下:

package com.mail;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.SimpleMailMessage;

public class SendTest {


    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring-mail.xml",
                "applicationContext.xml");
        MailSenderDemo sender = (MailSenderDemo)ac.getBean("MailSenderDemo");
        SimpleMailMessage mail = new SimpleMailMessage();
        mail.setTo("[email protected]");//收件人邮箱地址
        mail.setFrom("[email protected]");//收件人
        mail.setSubject("spring自带javamail发送的邮件");//主题
        mail.setText("hello this mail is from spring javaMail ");//正文
        sender.send(mail);
    }
}

最后要保证pom.xml中的配置jar的版本的准确,否侧可能会报类似找不到方法的错。。。比如spring-expression3.2.4会报错,换成4.2.6就可以了。

结果:
使用spring的JavaMailSender发送邮件_第2张图片

你可能感兴趣的:(spring,邮件,学习)