首先导入依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
然后创建email发送工具类
import org.springframework.stereotype.Component;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
@Component
public class MessageUtils {
private final String username = "your-email@example.com";
private final String password = "your-password";
public void sendMessage(String recipient, String message) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(username));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
msg.setSubject("通知消息");
msg.setText(message);
Transport.send(msg);
System.out.println("邮件发送成功!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
请注意,这里的邮件服务器设置 (smtp.example.com) 和端口 (465) 需要根据你的邮件服务商进行配置。
我这里使用的是QQ邮箱,SMTP服务器地址:smtp.qq.com,端口号:通常使用465(SSL加密)或587(TLS加密)
密码需要在这里获取,而不是你的QQ密码
这样就可以通过工具类发送email文件了