网上很多用Session方式那种发送,有点过于冗余,需要在POM文件里添加 依赖
有一个文章更详细可以参考:https://www.php.cn/manual/view/22279.html
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>5.0.4.RELEASE</version> </dependency>
import org.junit.Test;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
public class TestMail {
@Test
public void t1() throws MessagingException {
JavaMailSenderImpl mailSender =new JavaMailSenderImpl();
mailSender.setUsername("用户名");
mailSender.setPassword("密码");
mailSender.setHost("mail.hengrui.com");
//mailSender.setProtocol("smtp");
mailSender.setPort(587);//这个地方用587是因为Exchange邮件服务,多数是25
//简单邮件
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
simpleMailMessage.setFrom("test@hengrui.com");
simpleMailMessage.setTo("test2@hengrui.com");
simpleMailMessage.setSubject("验证码verycode");
simpleMailMessage.setText("您的验证码是600276<a href='baidu.com'>hello world</a>");
//mailSender.send(simpleMailMessage);
//html邮件
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
helper.setFrom("test@hengrui.com");
helper.setTo("test2@hengrui.com");
helper.setSubject("验证码verycode");
helper.setText("您的验证码是600276<br><a href='baidu.com'>hello world</a>",true);
helper.addAttachment("footer.png", new File("G:\\Image\\SUUMO\\footer.png"));
mailSender.send(mimeMessage);
}
}
标签:mailSender,helper,simpleMailMessage,import,SimpleMailMessage,mail,Java,邮件 From: https://www.cnblogs.com/life512/p/17130791.html