000 基于Spring boot发送邮件

  发送邮件的程序,使用QQ的服务器,经过测试,完全可行。可复现

一:准备工作

1.找到账号的授权码

  这个是程序需要使用的。

  在设置中查找。

2.新建项目的目录

  

二:完整的程序代码

1.pom.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 5     <modelVersion>4.0.0</modelVersion>
 6 
 7     <groupId>com.jun</groupId>
 8     <artifactId>message</artifactId>
 9     <version>1.0-SNAPSHOT</version>
10 
11     <dependencies>
12         <dependency>
13             <groupId>org.springframework</groupId>
14             <artifactId>spring-context-support</artifactId>
15             <version>5.1.7.RELEASE</version>
16         </dependency>
17         <dependency>
18             <groupId>org.springframework.boot</groupId>
19             <artifactId>spring-boot-starter-mail</artifactId>
20             <version>2.1.6.RELEASE</version>
21         </dependency>
22         <dependency>
23             <groupId>org.springframework.boot</groupId>
24             <artifactId>spring-boot-starter-test</artifactId>
25             <version>2.1.5.RELEASE</version>
26             <scope>test</scope>
27         </dependency>
28     </dependencies>
29 </project>

2.mail.properties

  这个需要写在测试类的配置文件中,因为在读取的时候,使用的是测试类中的配置文件

1 #======================当前自己发送端的信息====================
2 #邮件服务器主机名
3 mailserver.host=smtp.qq.com
4 #邮件服务器监听的端口号
5 mailserver.port=465
6 #用户名称
7 mailserver.username=1354440850@qq.com
8 #开启服务器后,生成的授权码
9 mailserver.password=ohikrolx

3.MailConfig

 1 package spittr.config;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.ComponentScan;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.context.annotation.PropertySource;
 7 import org.springframework.core.env.Environment;
 8 import org.springframework.mail.javamail.JavaMailSenderImpl;
 9 
10 import java.util.Properties;
11 
12 @Configuration
13 @ComponentScan("spittr")
14 @PropertySource("classpath:mail.properties")
15 public class MailConfig {
16     @Bean
17     public JavaMailSenderImpl mailSender(Environment env) {
18         //spring自带了一个MailSender的实现接口
19         JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
20         //邮件服务器主机名
21         mailSender.setHost(env.getProperty("mailserver.host"));
22         //邮件服务器监听的端口号
23         mailSender.setPort(Integer.parseInt(env.getProperty("mailserver.port")));
24         //用户名称
25         mailSender.setUsername(env.getProperty("mailserver.username"));
26         //密码,这里不是邮箱的密码,而是开启服务器后,生成的授权码
27         mailSender.setPassword(env.getProperty("mailserver.password"));
28         //ssl加密,需要加,否则无法运行
29         Properties props = System.getProperties();
30         final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
31         props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
32         mailSender.setJavaMailProperties(props);
33         return mailSender;
34     }
35 }

4.spitter.java

 1 package spittr.domain;
 2 
 3 public class Spitter {
 4     //编号
 5      private Long id;
 6     //用户名称
 7     private String username;
 8     //用户密码
 9     private String password;
10     //发件人的名称
11     private String fullName;
12     //收件人的邮箱
13     private String email;
14     //判断邮件是否带有附件
15     private boolean updateByEmail;
16 
17     public Spitter(Long id, String username, String password, String fullName, String email, boolean updateByEmail){
18         this.id=id;
19         this.username=username;
20         this.password=password;
21         this.fullName=fullName;
22         this.email=email;
23         this.updateByEmail=updateByEmail;
24     }
25 
26     public Long getId() {
27         return id;
28     }
29 
30     public void setId(Long id) {
31         this.id = id;
32     }
33 
34     public String getUsername() {
35         return username;
36     }
37 
38     public void setUsername(String username) {
39         this.username = username;
40     }
41 
42     public String getPassword() {
43         return password;
44     }
45 
46     public void setPassword(String password) {
47         this.password = password;
48     }
49 
50     public String getFullName() {
51         return fullName;
52     }
53 
54     public void setFullName(String fullName) {
55         this.fullName = fullName;
56     }
57 
58     public String getEmail() {
59         return email;
60     }
61 
62     public void setEmail(String email) {
63         this.email = email;
64     }
65 
66     public boolean isUpdateByEmail() {
67         return updateByEmail;
68     }
69 
70     public void setUpdateByEmail(boolean updateByEmail) {
71         this.updateByEmail = updateByEmail;
72     }
73 }

5.Sputtle

 1 package spittr.domain;
 2 
 3 import java.util.Date;
 4 
 5 public class Spittle {
 6     //编号
 7     private final Long id;
 8     //邮件的内容
 9     private final String text;
10     //发送的时间
11     private final Date postedTime;
12     //邮件信息的对象
13     private Spitter spitter;
14 
15     public Spittle(Long id, String text, Date postedTime, Spitter spitter) {
16         this.id = id;
17         this.text = text;
18         this.postedTime = postedTime;
19         this.spitter = spitter;
20     }
21 
22     public Long getId() {
23         return id;
24     }
25 
26     public String getText() {
27         return text;
28     }
29 
30     public Date getPostedTime() {
31         return postedTime;
32     }
33 
34     public Spitter getSpitter() {
35         return spitter;
36     }
37 
38     public void setSpitter(Spitter spitter) {
39         this.spitter = spitter;
40     }
41 }

6.SpitterMailService

 1 package spittr.email;
 2 
 3 import spittr.domain.Spittle;
 4 
 5 import javax.mail.MessagingException;
 6 
 7 public interface SpitterMailService {
 8     public abstract void sendSimpleSpittleEmail(String to, Spittle spittle);
 9     public abstract void sendSpittleEmailWithAttachment(String to, Spittle spittle) throws MessagingException;
10     public abstract void sendRichSpitterEmail(String to,Spittle spittle)throws MessagingException;
11 
12 }

7.SpitterMailServiceImpl

 1 package spittr.email;
 2 
 3 //import org.apache.velocity.app.VelocityEngine;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.core.io.ClassPathResource;
 6 import org.springframework.mail.SimpleMailMessage;
 7 import org.springframework.mail.javamail.JavaMailSender;
 8 import org.springframework.mail.javamail.MimeMessageHelper;
 9 import org.springframework.stereotype.Component;
10 import spittr.domain.Spittle;
11 
12 import javax.mail.MessagingException;
13 import javax.mail.internet.MimeMessage;
14 
15 @Component
16 public class SpitterMailServiceImpl implements SpitterMailService {
17     //邮件发送的核心类
18     private JavaMailSender mailSender;
19 
20     //通过构造方法将JavaMailSender依赖注入进来
21     @Autowired
22     public SpitterMailServiceImpl(JavaMailSender mailSender) {
23         this.mailSender = mailSender;
24     }
25 
26     /* 创建一封简单的邮件 */
27     public void sendSimpleSpittleEmail(String to, Spittle spittle) {
28         //通过这个对象封装信息,相当于信封
29         SimpleMailMessage message = new SimpleMailMessage();
30         //获取spittle对象中的收件人名字
31         String spitterName = spittle.getSpitter().getFullName();
32         //发件人
33         message.setFrom("1354440850@qq.com");
34         //收件人
35         message.setTo(to);
36         //邮件主题
37         message.setSubject("New spittle from " + spitterName);
38         //邮件内容
39         message.setText("haha,hui,这个是通过程序发送的!");
40         //发送邮件
41         mailSender.send(message);
42     }
43 
44     /* 创建一封带有图片附件的邮件 */
45     public void sendSpittleEmailWithAttachment(String to, Spittle spittle) throws MessagingException {
46         //通过邮件发送器的createMimeMessage方法构建可含附件的邮件
47         MimeMessage message = mailSender.createMimeMessage();
48         // 第一个参数是邮件的对象
49         // 第二个参数为true表示这个消息是multipart类型的消息(表示是带有附件的邮件)
50         // 第三个参数是防止中文乱码
51         MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
52         //获取收件人名,用于后面发送邮件做主题
53         String spitterName = spittle.getSpitter().getFullName();
54         //寄件人
55         helper.setFrom("1354440850@qq.com");
56         //收件人
57         helper.setTo(to);
58         //邮件的主题内容
59         helper.setSubject("New spittle from " + spitterName);
60         //邮件的发送内容
61         helper.setText(spitterName + " says: " + spittle.getText());
62         //通过路径获取图片附件
63         ClassPathResource couponImage = new ClassPathResource("/collateral/coupon.jpg");
64         //第一个参数是图片的名称,到时候收件人收到的附件名
65         //第二个参数是图片附件的资源
66         helper.addAttachment("Coupon.jpg", couponImage);
67         //send方法是发送邮件的方法
68         mailSender.send(message);
69 
70     }
71 
72 
73     /*  创建一封嵌套图片的文本邮件*/
74     public void sendRichSpitterEmail(String to, Spittle spittle) throws MessagingException {
75         //创建一封富文本邮件
76         MimeMessage message = mailSender.createMimeMessage();
77         //第二个参数表明传递进来的第一个参数是html文本
78         MimeMessageHelper helper = new MimeMessageHelper(message, true, "utf-8");
79         //发件人
80         helper.setFrom("1354440850@qq.com");
81         //收件人
82         helper.setTo(to);
83         //发送的邮件主题
84         helper.setSubject("New spittle from " + spittle.getSpitter().getFullName());
85         //cid:spitterLogo,标记一个变量,后面为这个变量添加一张图片
86         //第二个参数表示传递的第一个参数是html
87         helper.setText("<html><body><img src='cid:spittleLogo'>" + "<h4>" +
88                 spittle.getSpitter().getFullName() + "says...</h4>" + "<i>" + spittle.getText() +
89                 "</i>" + "</body></html>", true);
90         //创建一个变量存放图片
91         ClassPathResource image = new ClassPathResource("/collateral/coupon.jpg");
92         //为消息添加嵌入式的图片
93         helper.addInline("spittleLogo", image);
94         //发送邮件
95         mailSender.send(message);
96     }
97 }

8.测试类

 1 package spittr.email;
 2 
 3 import org.junit.Test;
 4 import org.junit.runner.RunWith;
 5 import org.springframework.beans.BeansException;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.context.ApplicationContext;
 8 import org.springframework.context.ApplicationContextAware;
 9 import org.springframework.mail.javamail.JavaMailSenderImpl;
10 import org.springframework.test.context.ContextConfiguration;
11 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
12 import spittr.config.MailConfig;
13 import spittr.domain.Spitter;
14 import spittr.domain.Spittle;
15 
16 import java.util.Date;
17 
18 @RunWith(SpringJUnit4ClassRunner.class)
19 @ContextConfiguration(classes=MailConfig.class)
20 public class SpitterMailServiceImplTest implements ApplicationContextAware {
21     @Autowired
22      private SpitterMailService mailService;
23 
24     @Autowired
25     private ApplicationContext applicationContext;
26 
27     @Test
28     public void sendSimpleSpittleEmail() throws Exception {
29         JavaMailSenderImpl beanName = (JavaMailSenderImpl)applicationContext.getBean("mailSender");
30 
31         Spitter spitter = new Spitter(1L, "", null, "coffie", "1354440850@qq.com", true);
32         Spittle spittle = new Spittle(1L, "Hiya!",new Date(),spitter);
33         //第一个参数是收件人,第二个参数是邮件
34 //        mailService.sendSimpleSpittleEmail(spitter.getEmail(),spittle);
35 //        mailService.sendSpittleEmailWithAttachment(spitter.getEmail(), spittle);
36         mailService.sendRichSpitterEmail(spitter.getEmail(),spittle);
37     }
38 
39     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
40         this.applicationContext=applicationContext;
41     }
42 }
原文地址:https://www.cnblogs.com/juncaoit/p/11164159.html