SpringBoot实现发送邮件

1.QQ邮箱发送邮件设置

首先登录QQ邮箱>>>登录成功后找到设置>>>然后找到邮箱设置>>>点击账户>>>找到POP3|SMTP服务>>>点击开启(开启需要验证,验证成功后会有一串授权码用于发送邮件使用)>>>验证成功 看图操作

SpringBoot实现发送邮件
SpringBoot实现发送邮件
SpringBoot实现发送邮件

授权码一定记得复制出来

**0.引入包**
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
**1.填写配置文件此处使用yml文件配置,使用yml配置记得注意格式哦,以免出错。**
spring:
 mail:
 default-encoding: UTF-8
 host: smtp.qq.com
 protocol: smtp
 username: 邮箱账号
 password: 服务授权码(不是QQ密码而是刚刚开启的POP3/SMTP服务 的授权码)
 smtp: 
 auth: true
 starttls: 
 enable: true
 required: true
**2.新建类实现发送邮件**
import java.io.File;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/** 
 * @author ADMIN
 * @date 2018年10月9日 下午3:59:59
 * @version 1.0 
 */
@RestController
public class MailController {
    
    
    @Autowired
    JavaMailSender jms;
    //发送文本消息,不带附件,内容是可以带html等标签之类的哦
    @GetMapping("/send")    
    public String send(){        
        //建立邮件消息        
        SimpleMailMessage mainMessage = new SimpleMailMessage();        
        //发送者        
        mainMessage.setFrom("发送者邮箱(需要在配置文件中一致)");        
        //接收者        
        mainMessage.setTo("接收者邮箱");        
        //发送的标题        
        mainMessage.setSubject("发送的标题");        
        //发送的内容        
        mainMessage.setText("发送的内容");        
        jms.send(mainMessage);        
        return "true";    
        
    }
    
    /**
     * 带附件发送,可多个附件 图片,doc都可以发送。
     * ADMIN
     * 2018年10月13日 下午12:31:13
     */
    @GetMapping("/sendFile")
    public void sendAttachmentsMail() {
        
        String [] fileArray={"C:\Users\Administrator\Desktop\图片\0.jpg","C:\Users\Administrator\Desktop\图片\aa.zip"};
        
        MimeMessage message=jms.createMimeMessage();
 try {
     MimeMessageHelper helper=new MimeMessageHelper(message,true);
 helper.setFrom("发送者邮箱(需要在配置文件中一致)");
 helper.setTo("接收者邮箱");
 helper.setSubject("发送标题");
 helper.setText("发送内容");
 //验证文件数据是否为空
 if(null != fileArray){
     FileSystemResource file=null;
     for (int i = 0; i < fileArray.length; i++) {
         //添加附件
         file=new FileSystemResource(fileArray[i]);
         helper.addAttachment(fileArray[i].substring(fileArray[i].lastIndexOf(File.separator)), file);
     }
 }
 jms.send(message);
 System.out.println("带附件的邮件发送成功");
 }catch (Exception e){
 e.printStackTrace();
 System.out.println("发送带附件的邮件失败");
 }
 }
}
PS:网易邮箱发送和QQ邮箱是一样的,只需要修改配置文件的host,username,password三个参数。将host改成:smtp.163.com,用户名和密码改成网易邮箱对应的就行

原文:https://blog.csdn.net/qq_34523482/article/details/83037551

猜你喜欢

转载自www.cnblogs.com/cl-rr/p/9785104.html