赞
踩
先导入依赖
- <dependency>
- <groupId>cn.hutool</groupId>
- <artifactId>hutool-all</artifactId>
- <version>5.8.4</version>
- </dependency>
- <dependency>
- <groupId>com.sun.mail</groupId>
- <artifactId>javax.mail</artifactId>
- <version>1.6.2</version>
- </dependency>
这里使用的阿里云的邮箱,由于qq邮箱需要一个授权码,这我不知道放在哪里,后续了解到后我会来补充。
- @SpringBootApplication
- public class App {
-
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- MailAccount account = new MailAccount();
- account.setHost("smtp.aliyun.com");
- account.setPort(25);
- account.setAuth(true);
- account.setFrom("发送的邮箱账户");
- //这里是发送邮箱账户
- account.setUser("发送的邮箱账户");
- //这里是发送邮箱密码
- account.setPass("发送的邮箱密码");
- //这里是需要待发送的邮箱账号
- ArrayList<String> toMaill = CollUtil.newArrayList("需要待发送的邮箱账号");
- MailUtil.send(account,toMaill , "测试", "邮件来自Hutool测试", false);
- }
-
- }

这个是可以发送成功的,现在我们来进行发送一个四位数的随机码来给邮箱
这里加入了随机数生成以及hutool的 StrUtil.format("您的验证码是:{}", c)字符串拼接
- @SpringBootApplication
- public class App {
-
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- MailAccount account = new MailAccount();
- account.setHost("smtp.aliyun.com");
- account.setPort(25);
- account.setAuth(true);
- account.setFrom("发送的邮箱账户");
- //这里是发送邮箱账户
- account.setUser("发送的邮箱账户");
- //这里是发送邮箱密码
- account.setPass("发送的邮箱密码");
- //这里是需要待发送的邮箱账号
- ArrayList<String> toMaill = CollUtil.newArrayList("需要待发送的邮箱账号");
- int c = RandomUtil.randomInt(1000,9999);
- String format = StrUtil.format("您的验证码是:{}", c);
- MailUtil.send(account,toMaill , "验证码", format, false);
- }
-
- }

现在我们进行将发送邮箱的方法给抽离成service方法,这样,以后我们使用发送邮箱的时候就可以直接拷贝到我们自己的代码中直接使用。
先建立一个MailService类
加入注解@Service然后使用@Value注解将写入配置文件的数据写入
- @Service
- public class MailService {
- @Value("${demo.mail.host}")
- private String mailHost;
-
- @Value("${demo.mail.port:25}")
- private Integer mailPort;
-
- @Value("${demo.mail.from}")
- private String mailFrom;
-
- @Value("${demo.mail.user}")
- private String mailUser;
-
- @Value("${demo.mail.pwd}")
- private String mailPwd;
-
- @Value("${demo.mail.to}")
- private List<String> mailTo;
-
- public void send() {
- MailAccount account = new MailAccount();
- account.setHost(this.mailHost);
- account.setPort(this.mailPort);
- account.setAuth(true);
- account.setFrom(this.mailFrom);
- account.setUser(this.mailUser);
- account.setPass(this.mailPwd);
- int code = RandomUtil.randomInt(1000, 9999);
- String body = StrUtil.format("您的验证码为:{}",code);
-
- MailUtil.send(account, this.mailTo, "验证码", body, false);
-
-
- }
-
- }

- demo.mail.host = smtp.aliyun.com
- demo.mail.port = 25
-
- demo.mail.from = 邮箱账户
-
- demo.mail.user = 邮箱账户
- demo.mail.pwd = 邮箱密码
-
- demo.mail.to = 待发送的邮箱账户
App调用
-
- @SpringBootApplication
- public class App {
-
- public static void main(String[] args) {
- ConfigurableApplicationContext run = SpringApplication.run(App.class, args);
- MailService bean = run.getBean(MailService.class);
- bean.send();
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。