引入包没有javax.mail报红。
引入maven
<!--发送邮件--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-email</artifactId> <version>1.5</version> </dependency> <!--发送邮件-->
import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMessage.RecipientType; import sun.management.snmp.util.MibLogger;
public static void main(String[] args) throws AddressException, MessagingException {
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");// 连接协议
properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
properties.put("mail.smtp.port", 465);// 端口号 587
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
properties.put("mail.debug", "false");// 设置是否显示debug信息 true 会在控制台显示相关信息
// 得到回话对象
Session session = Session.getInstance(properties);
// 获取邮件对象
Message message = new MimeMessage(session);
// 设置发件人邮箱地址
message.setFrom(new InternetAddress("14496453@qq.com"));
// 设置收件人地址
message.setRecipients(RecipientType.TO,
new InternetAddress[] { new InternetAddress("14496453@qq.com") });
// 设置邮件标题
message.setSubject("这是第一封Java邮件");
// 设置邮件内容
message.setText("内容为: 这是第一封java发送来的邮件。");
// 得到邮差对象
Transport transport = session.getTransport();
// 连接自己的邮箱账户
transport.connect("14496453@qq.com", "nauxacfidrgoc123");// 密码为刚才得到的授权码
// 发送邮件
transport.sendMessage(message, message.getAllRecipients());
//关闭
transport.close();
}
public static void send(String title,String content,String email) throws AddressException, MessagingException{
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");// 连接协议
properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
properties.put("mail.smtp.port", 465);// 端口号 587
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
properties.put("mail.debug", "false");// 设置是否显示debug信息 true 会在控制台显示相关信息
// 得到回话对象
Session session = Session.getInstance(properties);
// 获取邮件对象
Message message = new MimeMessage(session);
// 设置发件人邮箱地址
message.setFrom(new InternetAddress("14496453@qq.com"));
// 设置收件人地址
message.setRecipients(RecipientType.TO,
new InternetAddress[] { new InternetAddress(email) });
// 设置邮件标题
message.setSubject(title);
// 设置邮件内容
message.setText(content);
// 得到邮差对象
Transport transport = session.getTransport();
// 连接自己的邮箱账户
transport.connect("14496453@qq.com", "nauxacfidrgoc1111");// 密码为刚才得到的授权码
// 发送邮件
transport.sendMessage(message, message.getAllRecipients());
//关闭
transport.close();
}授权码。如何获取
点设置 ---- 帐户------



如果部署服务器。需要 解封服务器的25端口

站长微信:xiaomao0055
站长QQ:14496453