个人选择的发送服务服务器是QQ,所以要进行开启QQ邮箱的SMTP服务,过程如图所示:
在账户下设置开启SMTP服务,需记住显示的STMP密码,点击“开启”后发短信过去即可开启
EmailSendTest:
import org.junit.Test; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSenderImpl; import java.util.Properties; public class MailSendTest { @Test public void springEmailSender() throws IOException { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); //服务器SMTP域,可百度自行搜索对应域 mailSender.setHost("smtp.qq.com"); mailSender.setDefaultEncoding("UTF-8"); //发送方服务邮箱 mailSender.setUsername("你的账号@qq.com"); //发送方SMTP密码(并非你的QQ密码) mailSender.setPassword("16位的SMTP密码"); Properties props = new Properties(); //加载根目录下的mail.properties文件 props.load(ClassLoader.getSystemResourceAsStream("mail.properties")); //设置email会话 mailSender.setSession(Session.getInstance(props)); //新建邮件 SimpleMailMessage mailMessage = new SimpleMailMessage(); //收件人邮箱 mailMessage.setTo("接收方邮箱@163.com"); //邮件标题 mailMessage.setSubject("测试邮件"); //邮件发送方邮箱,若与username值相同将抛出from与username不符的异常 mailMessage.setFrom("发送方邮箱@qq.com"); //邮件内容 mailMessage.setText("a test email"); //进行邮件发送 mailSender.send(mailMessage); } }
根目录下的资源文件mail.properties:
#若不设置将抛出iis security异常
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.port=465
个人成功测试图如下: