JavaMail在SSM框架中的应用

 SSM框架的搭建 在我的博客里有,用Maven搭建 和 jar包搭建的都有,可以看我的博客,好了,直接开始JavaMail 在SSM框架中的应用

我只贴出来关键的代码 ,大家可以参照一下

第一步  Maven 添加Mail支持

 
    
      commons-fileupload
      commons-fileupload
      1.3.1
    
    
      commons-io
      commons-io
      2.4
    
       
        
            javax.mail
            mail
            1.4.5
        





第二步  先写pojo类 (就是从前端传来的主题,内容什么什么的)

package cn.bssys.po;

import java.util.Arrays;
import java.util.Date;

public class Email {

    private String recipient[];//因为会发送邮件给好几个人,所以用数组来代表每个接收者的email地址

    private String sender;

    private String subject;

    private String content;

    private String attachment;

    private Date sendDate;

    public String[] getRecipient() {
        return recipient;
    }

    public void setRecipient(String[] recipient) {
        this.recipient = recipient;
    }

    public String getSender() {
        return sender;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAttachment() {
        return attachment;
    }

    public void setAttachment(String attachment) {
        this.attachment = attachment;
    }

    public Date getSendDate() {
        return sendDate;
    }

    public void setSendDate(Date sendDate) {
        this.sendDate = sendDate;
    }

    @Override
    public String toString() {
        return "Email{" +
                "recipient=" + Arrays.toString(recipient) +
                ", sender='" + sender + '\'' +
                ", subject='" + subject + '\'' +
                ", content='" + content + '\'' +
                ", attachment='" + attachment + '\'' +
                ", sendDate=" + sendDate +
                '}';
    }
}


第三步  先写接口 (写到这的时候,被我的小组长说了,因为我把用到的函数都写在了接口里,但是用到的就一个函数而已。。。以后不要犯这种错误啦)

package cn.bssys.service;

import cn.bssys.po.Email;

import javax.mail.Message;
import javax.mail.Session;

/**
 * Created by LENOVO on 2017/8/3.
 */
public interface MailService  {


    public boolean sendEamil(Email email) ;


}

第四步  写实现接口类
package cn.bssys.service.impl;

import cn.bssys.po.Email;
import cn.bssys.service.MailService;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;



@Service("mailService")//SSM框架 注解,让Spring明白它是一个Service组件(告诉spring创建一个实现类的实例)
//mailService 就是在为这个bean 取名字
 public class MailServiceImpl extends Thread implements MailService{
    private Session session = null;

    private Properties prop = null;

    private Transport ts = null;

    public MailServiceImpl() throws Exception {
        System.setProperty("mail.mime.charset","UTF-8");
        prop = new Properties();
        //获取properties 的内容,注意 使用各种邮箱发送邮件,properties里面的内容是不一样的!!
      InputStream in = this.getClass().getResourceAsStream("/mail.properties");
        prop.load(in);

    }

    public void connect()throws Exception{
        session = Session.getInstance(prop);
        session.setDebug(true);
        ts = session.getTransport();
//       ts.connect(host, username, password);
//      163邮箱connect方法,第三个参数应该是授权码,而不是密码.
        String host = prop.getProperty("host");
        String username = prop.getProperty("username");
        String password = prop.getProperty("password");
        ts.connect(host, username, password);

    }

    @Override
    public boolean sendEamil(Email email) {
        boolean flag = false;
        try {
            connect();
            String from = prop.getProperty("from");
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            for (int i = 0; i < email.getRecipient().length; i++) {
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(email.getRecipient()[i]));
            }
//                message.setSubject(email.getSubject());
                message.setSubject(email.getSubject(),"UTF-8");
                String info = email.getContent();
                message.setContent(info, "text/html;charset=UTF-8");
                if(email.getAttachment()!=null){
                    MimeBodyPart attach = new MimeBodyPart();
                    DataHandler dh = new DataHandler(new FileDataSource(email.getAttachment()));
                    attach.setDataHandler(dh);
                    attach.setFileName(dh.getName());
                    MimeMultipart mp = new MimeMultipart();
                   // mp.addBodyPart(text);
                    mp.addBodyPart(attach);
                    mp.setSubType("mixed");
                    message.setContent(mp);
                }
                message.saveChanges();
                ts.sendMessage(message, message.getAllRecipients());
               ts.close();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}

第五步 mail.properties  我用的qq邮箱   如果用别的邮箱,写的也不同

from=*******@qq.com
username=*******
password=********
host=smtp.qq.com
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.port=465
mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
第六步 controller层

package cn.bssys.controller;

import cn.bssys.po.Email;
import cn.bssys.service.MailService;
import cn.bssys.service.StudentService;
import cn.bssys.service.impl.MailServiceImpl;
import cn.bssys.util.PageUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;


@Controller
@RequestMapping(value = "/mail",produces = {"application/json;charset=UTF-8"} )
public class MailController {
    @Autowired
    MailService mailService;
    @Autowired
    StudentService studentService;

    @RequestMapping("/send")
    @ResponseBody
    public String sendEmail(Email email, @RequestParam(value = "file",required = false)CommonsMultipartFile file, HttpServletRequest request) throws Exception {
        if (!file.isEmpty()){ //判断有没有附件 
            email.setAttachment(PageUtil.uploadAnnex(request,file,"cache","email_attachment"));
        }
        for (int i = 0;i < email.getRecipient().length;i++){
            email.getRecipient()[i] = studentService.getObjectByPrimaryKey(Integer.parseInt(email.getRecipient()[i])).getEmail();
        }

        if (mailService.sendEamil(email)){
            return JSON.toJSONString("发送成功");
        }else {
            return JSON.toJSONString("发送失败,请稍后再试");
        }
    }


}





你可能感兴趣的:(javaweb知识)