Email 工具类
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.4</version>
</dependency>
package com.midea.EMAIL;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* 电子邮件工具类
*
* @author Administrator
*/
public class MailUtil {
/*以下只需要修改如下几个地方 完成QQ邮箱[email protected]账号发送的邮件
props.setProperty("mail.smtp.host", "smtp.qq.com"); //设置主机地址 第一个参数不变, 第二个参数只修改中间的换成 qq sina google ....
Address fromAddr = new InternetAddress("[email protected]"); //设置发送邮件的账号
transport.connect("smtp.qq.com", "[email protected]", "403c7168ddbd8cq"); //第一个参数不修改 第二个参数发送邮件的账号 第三个参数服务器授权码 :gdnbizbixcaubcq
* */
//实现邮件发送的方法 to:接收人email subject:邮件主题 context:邮件的正文内容
public static void sendMsg(String to, String subject, String content) throws Exception {
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.qq.com"); //设置主机地址 smtp.qq.com smtp.sina.com
props.setProperty("mail.smtp.auth", "true");//认证
//2.产生一个用于邮件发送的Session对象
Session session = Session.getInstance(props);
//3.产生一个邮件的消息对象
MimeMessage message = new MimeMessage(session);
//4.设置消息的发送者
Address fromAddr = new InternetAddress("[email protected]");
message.setFrom(fromAddr);
//5.设置消息的接收者
Address toAddr = new InternetAddress(to);
//TO 直接发送 CC抄送 BCC密送
message.setRecipient(MimeMessage.RecipientType.TO, toAddr);
//6.设置主题
message.setSubject(subject);
//7.设置正文
message.setText(content);
//8.准备发送,得到火箭
Transport transport = session.getTransport("smtp");
//9.设置火箭的发射目标
//user: 从哪个邮箱地址发送
//password: 邮箱服务器的授权码
transport.connect("smtp.qq.com", "[email protected]", "gdnbizbixcaubciq");
//10.发送
transport.sendMessage(message, message.getAllRecipients());
//11.关闭
transport.close();
}
}
使用
MailUtil.sendMsg("[email protected]","主题","邮件的正文内容");标签:qq,smtp,发送,设置,mail,message,com,Email From: https://www.cnblogs.com/EthanLoveMath/p/17382926.html