163网易邮箱发邮件的服务
首先你需要在163开通一下服务
开通之后会显示授权码,拿好了别丢了
Spring配置文件
到SpringBoot里进行配置
java
spring.mail.host=smtp.163.com
# 填你的邮箱↓
spring.mail.username=15032895039@163.com
# 填你的授权码
spring.mail.password=haorenyishenpinan
spring.mail.port=25
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
除了邮箱
和授权码
其实别的地方都一样。
pom里添加依赖
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>3.0.0</version>
</dependency>
编写后端处理请求->发送右键的代码
配好之后,可以写一个接收发邮箱的请求
这里为了简单写,就把目标邮箱什么的都写在后端了
controller
java
package com.example.demo.mail;
import jakarta.mail.MessagingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/email")
public class EmailController {
@Autowired
private EmailService emailService;
@GetMapping("/send")
public String sendEmail() {
try {
// 第一个参数是目标邮箱,就是你要发到哪儿,可以填自己qq邮箱
emailService.sendEmail("3131015733@qq.com", "测试发送邮箱服务", "5873");
return "Email sent successfully to " + "3131015733@qq.com";
} catch (MessagingException e) {
return "Error sending email: " + e.getMessage();
}
}
}
java
package com.example.demo.mail;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
@Service
public class EmailService {
private final MailSender mailSender;
public EmailService(MailSender mailSender) {
this.mailSender = mailSender;
}
public void sendEmail(String to, String subject, String text) throws MessagingException {
System.out.println("尝试发送邮箱");
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom("15032895039@163.com");
message.setTo(to);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
System.out.println("发送成功");
}
}
测试
在浏览器上输入
localhost:8080/email/send
就ok了