springboot javamail_spring boot入门

springboot javamail_spring boot入门一、导入相关依赖在springboot中配置MultipartResolver注:使用了Spring的MultipartFile来接受文件上传才要配置的二、controller(service)

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

一、导入相关依赖

<!--邮件发送-->
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.5</version>
</dependency>

在springboot中配置MultipartResolver

注:使用了Spring的MultipartFile来接受文件上传才要配置的

//配置文件上传
@Bean(name = "multipartResolver")
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver resolver = new CommonsMultipartResolver();
    resolver.setDefaultEncoding("UTF-8");
    // resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常
    resolver.setResolveLazily(true);
    resolver.setMaxInMemorySize(40960);
    // 上传文件大小 5G
    resolver.setMaxUploadSize(5 * 1024 * 1024 * 1024);
    return resolver;
}

二、controller(service)

这里的接口接收的字符串格式为[xxxxx@qq.com;xxxxx@163.com]这样的,入参的形式随意,最后调用工具类传入数组即可

import com.sanyu.tender.util.mailSend.MailSend;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:huang
 * @Date:2019-09-18 18:55
 * @Description:邮件发送接口
 */
@Controller
public class sendMailController {

    @Autowired
    private MailSend mailSend;

    @RequestMapping("/mail_send_show")
    public String showSendMail(){
        return "mail-send";
    }

    //接受文件上传
    @RequestMapping("/mail_send")
    @ResponseBody
    public Map sendMail(String title,String content,String email,MultipartFile file){
        Map<String,Object> map = new HashMap<>(16);

        //获取地址字符串并截取放入集合
        ArrayList<String> list = new ArrayList<>();
        String[] emailArr = email.split(";");
        for (int i = 1;i<emailArr.length;i++){
            list.add(emailArr[i]);
        }

        map.put("status","success");
        try {
            //调用javaMail邮件发送工具类
            mailSend.send(list,title,content,file);
        }catch (Exception e){
            e.getStackTrace();
            map.put("status","false");
        }
        return map;
    }

}

三、javaMail邮件发送工具类代码

/**
 * @Author:huang
 * @Date:2019-09-17 20:29
 * @Description:邮件发送工具类
 */
@Component
public final class MailSend {

    //发件人账号和授权码
    private static final String MY_EMAIL_ACCOUNT = "xxxx@163.com";
    private static final String MY_EMAIL_PASSWORD = "xxxx";

    //SMTP服务器(这里用的163 SMTP服务器)
    private static final String MEAIL_163_SMTP_HOST = "smtp.163.com";

    //端口号
    private static final String SMTP_163_PORT = "25";

    //message对象
    private MimeMessage message;

    {
        //创建发件邮箱对象
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", MEAIL_163_SMTP_HOST);
        properties.setProperty("mail.smtp.port", SMTP_163_PORT);
        properties.setProperty("mail.smtp.socketFactory.port", SMTP_163_PORT);
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.socketFactory.class", "SSL_FACTORY");
        //登录
        Session session = Session.getInstance(properties, new Authenticator() {
            // 设置认证账户信息
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MY_EMAIL_ACCOUNT, MY_EMAIL_PASSWORD);
            }
        });
        session.setDebug(false);

        //创建邮件对象
        System.out.println("创建发件人邮箱");
        message = new MimeMessage(session);
    }

    /**
     * 发送邮件
     * @param to 收件人邮箱的集合
     * @param title 邮件标题
     * @param content 邮件内容
     * @param file 通过表单上传的MultipartFile文件
     * @return 根据方法执行情况返回一个Boolean类型的值
     */
    public boolean send(ArrayList<String> to, String title, String content,MultipartFile file){
        File tempFile = null;

        try {
            //发件人
            message.setFrom(new InternetAddress(MY_EMAIL_ACCOUNT));
            //收件人
            setAccepter(to);
            //标题
            message.setSubject(title);

            //当存在附件的情况下,内容将和附件一起上传
            if (file != null){
                //添加附件和内容
                tempFile = getFile(file);
                setMultipartAndContent(tempFile,content);
            }else {
                //内容
                message.setContent(content, "text/html;charset=UTF-8");
            }

            //发送时间
            message.setSentDate(new Date());
            message.saveChanges();
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }

        //发送邮件
        System.out.println("准备发送");
        try {
            Transport.send(message);

            //当存在附件的情况下发送完邮件以后删除上传到服务器的文件
            if (file != null){
                deleteServerFile(tempFile);
            }

        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送失败");
            return false;
        }
        System.out.println("发送完成");
        return true;
    }

    /**
     * 添加收件人
     * @param list 存放收件人邮箱的集合
     */
    private void setAccepter(ArrayList<String> list){
        //创建收件人地址数组
        InternetAddress[] sendTo = new InternetAddress[list.size()];
        //把list中的数据转至数组
        for (int i = 0; i < list.size(); i++) {
            //System.out.println("发送到:" + list.get(i));
            try {
                sendTo[i] = new InternetAddress(list.get(i));
            } catch (AddressException e) {
                e.printStackTrace();
                return;
            }
        }
        //填入message对象
        try {
            message.setRecipients(MimeMessage.RecipientType.TO,sendTo);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置附件和内容(当存在附件的情况下,必须通过此方法以发送内容,否则只显示附件而不显示内容)
     * @param file 要添加到message对象的文件
     * @param content 要添加到message对象的内容
     */
    private void setMultipartAndContent(File file,String content) {
        // 一个Multipart对象包含一个或多个BodyPart对象,来组成邮件的正文部分(包括附件)。
        MimeMultipart multiPart = new MimeMultipart();

        //内容模块
        MimeBodyPart partText = new MimeBodyPart();
        // 文件模块
        MimeBodyPart partFile = new MimeBodyPart();
        try {
            //添加内容
            partText.setContent(content,"text/html;charset=UTF-8");
            //添加文件
            partFile.attachFile(file);
            // 设置在收件箱中和附件名 并进行编码以防止中文乱码
            partFile.setFileName(MimeUtility.encodeText(file.getName()));

            multiPart.addBodyPart(partText);
            multiPart.addBodyPart(partFile);
            message.setContent(multiPart);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    /**
     * 将通过表单上传的MultipartFile文件上传到服务器并转换为File
     * @param file 通过表单上传的MultipartFile文件
     * @return 返回上传到服务器并转换完成的文件
     */
    private File getFile(MultipartFile file){
        //得到MultipartFile文件
        MultipartFile multipartFile = file;
        File f = null;

        //创建文件
        System.out.println("上传文件:"+multipartFile.getOriginalFilename());
        f = new File(multipartFile.getOriginalFilename());

        //得到文件流。以文件流的方式输出到新文件
        try (InputStream in  = multipartFile.getInputStream(); OutputStream os = new FileOutputStream(f)){
            // 可以使用byte[] ss = multipartFile.getBytes();代替while
            int n;
            byte[] buffer = new byte[4096];
            while ((n = in.read(buffer,0,4096)) != -1){
                os.write(buffer,0,n);
            }
            BufferedReader bufferedReader = new BufferedReader(new FileReader(f));
            bufferedReader.close();
        }catch (IOException e){
            e.printStackTrace();
        }

        //输出file的URL
        try {
            System.out.println(f.toURI().toURL().toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        //输出文件的绝对路径
        System.out.println(f.getAbsolutePath());

        return new File(f.toURI());
    }

    /**
     * 删除文件
     * @param file 要删除的文件
     * @return 根据方法执行情况返回一个Boolean类型的值
     */
    private boolean deleteServerFile(File file){
        return file.delete();
    }

}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/170833.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • zookeeper — 第二章 zookeeper 安装与配置说明

    zookeeper — 第二章 zookeeper 安装与配置说明

    2022年3月12日
    48
  • VMware虚拟机安装黑群晖7.0教程

    VMware虚拟机安装黑群晖7.0教程教程仅供参考,不当之处多多理解。该篇教程主要讲解黑群晖(DS918+)的安装Tip:本教程本教程只用于个人学习使用,有条件,长期使用的朋友推荐从正规官方渠道入手。1.首先安装VMware虚拟机双击安装文件进行安装…

    2022年7月14日
    194
  • mybatis log plugin 激活码【2021.7最新】

    (mybatis log plugin 激活码)这是一篇idea技术相关文章,由全栈君为大家提供,主要知识点是关于2021JetBrains全家桶永久激活码的内容IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.htmlMLZPB5EL5Q-eyJsa…

    2022年3月21日
    113
  • WSGI、Flask及Werkzeug三者之间的关系

    WSGI、Flask及Werkzeug三者之间的关系目录一、WSGI是什么?二、Werkzeug是什么三、Flask的WSGI实现一、WSGI是什么?WSGI是一套接口规范。一个WSGI程序用以接受客户端请求,传递给应用,再返回服务器的响应给客户端。WSGI程序通常被定义成一个函数,当然你也可以使用类实例来实现。下图显示了python中客户端、服务器、WSGI、应用之间的关系:从下往上开始介绍:客户端:浏览器或者app。web服务器:Web服务器是指驻留于因特网上某种类型计算机的程序。当Web浏览器(客户端)连到服务.

    2022年9月28日
    0
  • getenforce命令–Linux命令应用大词典729个命令解读[通俗易懂]

    getenforce命令–Linux命令应用大词典729个命令解读[通俗易懂]使用getenforce命令可以显示当前SELinux的应用模式,是强制、执行还是停用。

    2022年6月27日
    33
  • android的适配器作用,适配器在Android中的作用是什么?

    android的适配器作用,适配器在Android中的作用是什么?适配器在Android中的作用是什么?我想知道在Android环境中何时,何地以及如何使用适配器。来自Android开发者文档的信息对我来说不够,我希望得到更详细的分析。11个解决方案39votesAndroid中的适配器基本上是UI组件和将数据填充到UI组件的数据源之间的桥梁例如,通过使用数据源数组中的列表适配器来填充列表(UI组件)。success_anilanswered2019-06…

    2022年6月11日
    31

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号