JavaMail--发送简单邮件


//发邮件用到的两个包
"org.springframework:spring-context-support:$springVersion",
"javax.mail:mail:1.4.7"

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <servlet>
        <servlet-name>mvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:Spring_mvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>mvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>

Spring_mvc.xml

<?xml version="1.0" encoding="UTF-8"?>

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    
    

    
    package="text"/>


    class="org.springframework.mail.javamail.JavaMailSenderImpl">
        
        
        
        
        
            
                smtp
                true
                true

                true
            
        
    

UserService.java

package text;


import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;

@Service
public class UserService {
   //@Resource
   // private JavaMailSender mailSender;//,mailSender找Spring_mvc.xml的id的
    @Resource
    private  MailSender mailSender;
    public void sendMailDemo() throws MessagingException {

       SimpleMailMessage mailMsg = new SimpleMailMessage();//只支持文字
        mailMsg.setFrom("8962@qq.com");//发件人
        mailMsg.setTo("11717@qq.com");//收件人
        mailMsg.setSubject("很棒哦,今晚你回去扫地了");//邮件标题
        mailMsg.setText("哦哦"); //测试内容
        mailSender.send(mailMsg);//发送*

    }
   @Test
    public void test() throws MessagingException {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("Spring_mvc.xml");
      mailSender = (MailSender) ctx.getBean("mailSender");



        };
    }

这样就可以简单的发文字邮件了!!!