准备::Maven项目
1.导入jar包:
com.sun.mail javax.mail1.6.2
2.编写 MailUtil工具类
package com.wanshi.spring.utils; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class MailUtil { public static void sendTextMail(final String to, final String subject,final String content){ String host = "smtp.163.com"; String user = ""; //你的邮箱账号 String password= ""; //你的邮箱授权码 try { sendTextMail(host, user, password, to, subject, content); } catch (Exception e) { e.printStackTrace(); } } public static void sendTextMail(final String host, final String user, final String password, final String to, final String subject, final String content) throws Exception { // 相关的属性 Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.timeout", "20000"); // 设置 电子邮箱和密码,做发送邮件的授权 Authenticator auth = new Authenticator() { @Override protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password); } }; Session session = Session.getInstance(props, auth); // 定义要发送邮件的内容 MimeMessage msg = new MimeMessage(session); // 设置发送放的电子邮箱 msg.setFrom(new InternetAddress(user)); // 接收方的电子邮箱 msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 标题,主题 msg.setSubject(subject); // 发送的文本内容 msg.setText(content); // 保存邮件 msg.saveChanges(); Transport.send(msg, msg.getAllRecipients()); } }
3.测试类:
import com.wanshi.spring.utils.MailUtil; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class test { @Test public void test(){ String content = ""; //内容 MailUtil.sendTextMail("要接收的邮箱", "标题", content); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)