springboot-mysql-email集成

springboot发送邮件案例

邮件jar配置:

<!-- mail -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

application.properties配置:

#jndi propertiesa
spring.mail.host=mail.qq.com
spring.mail.port=25
spring.mail.username=osda@qq.com
spring.mail.password=123@qq
spring.mail.default-encoding=UTF-8
spring.mail.from=osda@qq.com

jsp页面设置:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
      <form action="<%=request.getContextPath()%>/test/sendMail.do" method="post" enctype="multipart/form-data">
            接收邮箱:<input type="text" name="email"><br>
            标题:<input type="text" name="title"><br>
            附件:<input type="file" name="file" multiple="multiple"><br>
            内容:<textarea name="context" id="" cols="30" rows="10"></textarea><br>
            <input type="submit" value="发送">
      </form>
</body>
</html>

邮件接口访问层:

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.MultipartFile;
import com.szxx.mysql.bean.Email;
import com.szxx.mysql.service.impl.IMailServiceImpl;


/**
 *@Title: MailSendController
 *@date 2019年10月8日 上午11:22:10
 *@Description:
 *
 */

@Controller
@RequestMapping("/test")
public class MailSendTestController {

              @Autowired
              IMailServiceImpl mailServiceImpl;
            
              //进入index页面//http://127.0.0.1:8097/test/email.do
              @RequestMapping("/email.do")
              public String index(){
                    return "test/sendemail";
              }

              @RequestMapping(value="/sendMail.do")
              @ResponseBody
              public String send2(@RequestParam("file") MultipartFile[] file,Email email) {

                    mailServiceImpl.sendAttachmentsMail(email.getEmail(), email.getTitle(), email.getContext(),file);
                    //mailServiceImpl.sendInlineResourceMail(email.getEmail(), email.getTitle(), email.getContext(), file, "img11");

                    return "发送成功";
              }
}

 

邮件接口:

import javax.mail.MessagingException;
import org.springframework.web.multipart.MultipartFile;

/**
 *@Title: IMailServer
 *@date 2019年10月8日 上午10:35:40
 */
public interface IMailService {

   /**
     * 发送文本邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     */
    public void sendSimpleMail(String to, String subject, String content);


   /**
     * 发送HTML邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @throws MessagingException
     */
    public void sendHtmlMail(String to, String subject, String content);

    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId);

    /**
     * 发送带附件的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @param filePath 附件
     */
    public void sendAttachmentsMail(String to, String subject, String content, String filePath);

    /**
     * 发送带附件的邮件
     * @param to 收件人
     * @param subject 主题
     * @param content 内容
     * @param filePath 附件
     */
     public void sendAttachmentsMail(String to, String subject, String content, MultipartFile[] file);

     public void sendInlineResourceMail(String to, String subject, String content, MultipartFile[] files, String rscId);

}

邮件接口实现类:

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 *@Title: IMailServerImpl
 *@date 2019年10月8日 上午10:36:12
 *@Description:
 *
 */
@Service
public class IMailServiceImpl implements com.szxx.mysql.service.IMailService{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * Spring Boot 提供了一个发送邮件的简单抽象,使用的是下面这个接口,这里直接注入即可使用
     */
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 配置文件中我的qq邮箱
     */
    @Value("${spring.mail.from}")

    private String from;

              //普通邮件
              @Override
              public void sendSimpleMail(String to, String subject, String content) {

                            logger.info("*****sendSimpleMail,邮件发送开始*******收件人:"+to+",主题:"+subject+",内容:"+content);
                            SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from); // 邮件发送者
        message.setTo(to); // 邮件接受者
        message.setSubject(subject); // 主题
        message.setText(content); // 内容
        mailSender.send(message);

              }

              //html邮件
              @Override
              public void sendHtmlMail(String to, String subject, String content) {

                            logger.info("*****sendHtmlMail,邮件发送开始*******收件人:"+to+",主题:"+subject+",内容:"+content);
                            MimeMessage message = mailSender.createMimeMessage();
                  //true 表⽰示需要创建⼀一个 multipart message
                  MimeMessageHelper helper;

                            try {
                                          helper = new MimeMessageHelper(message, true);
                                          helper.setFrom(from);
                                helper.setTo(to);
                                helper.setSubject(subject);
                                helper.setText(content, true);
                                mailSender.send(message);
                            } catch (MessagingException e) {
                                          e.printStackTrace();

                            }
                 
              }

              //发送附件
              @Override
              public void sendAttachmentsMail(String to, String subject, String content, String filePath) {

                            logger.info("*****sendAttachmentsMail,邮件发送开始*******收件人:"+to+",主题:"+subject+",内容:"+content);
                            MimeMessage message = mailSender.createMimeMessage();
                  MimeMessageHelper helper;

                            try {
                                          helper = new MimeMessageHelper(message, true);
                                          helper.setFrom(from);
                                helper.setTo(to);
                                helper.setSubject(subject);
                                helper.setText(content, true);
                                FileSystemResource file = new FileSystemResource(new File(filePath));
                                String fileName = file.getFilename();
                                helper.addAttachment(fileName, file);
                                mailSender.send(message);
                            } catch (MessagingException e) {
                                e.printStackTrace();

                            }
                 
              }

              //发送附件
                            @Override
                            public void sendAttachmentsMail(String to, String subject, String content, MultipartFile[] files) {

                                          logger.info("*****sendAttachmentsMail,邮件发送开始*******收件人:"+to+",主题:"+subject+",内容:"+content);
                                          MimeMessage message = mailSender.createMimeMessage();
                                MimeMessageHelper helper;
                                          try {
                                                        helper = new MimeMessageHelper(message, true);
                                                        helper.setFrom(from);
                                              helper.setTo(to);
                                              helper.setSubject(subject);
                                              helper.setText(content, true);
                                              //FileSystemResource file = new FileSystemResource(new File(filePath));
                                              File toFile = null;
                                 InputStream ins = null;
                          for(int i=0;i<files.length;i++) {
                            ins = files[i].getInputStream();
                                                   toFile = new File(files[i].getOriginalFilename());
                              inputStreamToFile(ins, toFile);
                              ins.close();
                            if (files[i] != null) {
                                          FileSystemResource file = new FileSystemResource(toFile);
                                          String fileName = file.getFilename();
                                                       helper.addAttachment(fileName, file);
                                                   }

                                 }

                                              mailSender.send(message);
                                          } catch (Exception e) {
                                                        e.printStackTrace();
                                          }
                               
                            }


    //发送图片
              @Override
              public void sendInlineResourceMail(String to, String subject, String content, MultipartFile[] files, String rscId) {

                            logger.info("*****sendInlineResourceMail,邮件发送开始*******收件人:"
                               +to+",主题:"+subject+",内容:"+content+",files:"+files.length+",rscId:"+rscId);
                            MimeMessage message = mailSender.createMimeMessage();
                  MimeMessageHelper helper;
                            try {
                                          helper = new MimeMessageHelper(message, true);
                                          helper.setFrom(from);
                                helper.setTo(to);
                                helper.setSubject(subject);
                                helper.setText(content, true);
                                //File file = new File(rscPath);
                               
                                File toFile = null;
                   InputStream ins = null;
            for(int i=0;i<files.length;i++) {
              ins = files[i].getInputStream();
                                     toFile = new File(files[i].getOriginalFilename());
                inputStreamToFile(ins, toFile);
                ins.close();
              if (files[i] != null) {
                            FileSystemResource res = new FileSystemResource(toFile);
                                     helper.addInline(rscId, res);
                                     }
                   }

                                mailSender.send(message);
                            } catch (Exception e) {
                                          e.printStackTrace();
                            }
                 
              }


//发送图片
                            @Override
                            public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
                                          logger.info("*****sendInlineResourceMail,邮件发送开始*******收件人:"

                                             +to+",主题:"+subject+",内容:"+content+",rscPath:"+rscPath+",rscId:"+rscId);
                                          MimeMessage message = mailSender.createMimeMessage();
                                MimeMessageHelper helper;
                                          try {
                                                        helper = new MimeMessageHelper(message, true);
                                                        helper.setFrom(from);

                                              helper.setTo(to);
                                              helper.setSubject(subject);
                                              helper.setText(content, true);
                                              File file = new File(rscPath);
                                              FileSystemResource res = new FileSystemResource(file);
                                              helper.addInline(rscId, res);
                                              mailSender.send(message);
                                          } catch (MessagingException e) {
                                                        e.printStackTrace();
                                          }

                            }

             

              public static void inputStreamToFile(InputStream ins, File file) {

                  try {
                      OutputStream os = new FileOutputStream(file);
                      int bytesRead = 0;
                      byte[] buffer = new byte[8192];
                      while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                          os.write(buffer, 0, bytesRead);
                      }

                      os.close();
                      ins.close();

                  } catch (Exception e) {

                      e.printStackTrace();

                  }

              }



}

 

 

       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot项目中集成MySQL数据库,可以通过以下步骤进行配置: 1. 添加MySQL依赖:在项目的pom.xml文件中添加MySQL连接器的依赖,例如: ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> ``` 2. 配置数据库连接信息:在项目的application.properties或application.yml文件中配置MySQL数据库的连接信息,包括URL、用户名和密码,例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=root spring.datasource.password=123456 ``` 3. 创建数据源:在Spring Boot的配置类中创建数据源,例如: ```java @Configuration public class DataSourceConfig { @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } } ``` 4. 使用JdbcTemplate或Spring Data JPA进行数据库操作:可以使用JdbcTemplate或Spring Data JPA来执行SQL语句或进行ORM操作。例如,使用JdbcTemplate: ```java @Repository public class UserRepository { private final JdbcTemplate jdbcTemplate; public UserRepository(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public void save(User user) { String sql = "INSERT INTO users (name, email) VALUES (?, ?)"; jdbcTemplate.update(sql, user.getName(), user.getEmail()); } // 其他数据库操作方法... } ``` 以上是Spring Boot项目集成MySQL数据库的基本步骤。关于"discard long time none received connection"错误,可能是由于数据库连接池配置不当导致的。你可以尝试调整数据库连接池的配置参数,例如增加最大连接数、设置连接超时时间等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值