java发送邮件实例

1、选择一个邮箱开通smtp服务

Java-工具类-发送邮件实例_java

2、代码

依赖pom

<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.4</version>
</dependency>

java代码

package fltest;

import utils.ConfigProperty;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class SendMessage {

public static String address = "chosenfl@163.com";
public static String password = "DPTYFYZNYUXNKXRS";// 邮箱授权码
public static String host = "smtp.163.com";
public static String port = "25";
public static String auth = "true";
public static String starttls = "true";
public static String name = "独孤飞磊";
public static String transType = "smtp";

public static boolean sendMail(String subject, String context, String[] recipientArr) {
boolean flag = true;

// 建立邮件会话
Properties pro = new Properties();
pro.setProperty("mail.smtp.from", address);
pro.setProperty("mail.smtp.password", password);
pro.setProperty("mail.smtp.host", host);
pro.setProperty("mail.smtp.port", port);
pro.setProperty("mail.smtp.auth", auth);
pro.setProperty("mail.smtp.starttls.enable", starttls);

Session s = Session.getInstance(pro); // 根据属性新建一个邮件会话
s.setDebug(true);
MimeMessage message = new MimeMessage(s);// 由邮件会话新建一个消息对象
try {
// 设置邮件
InternetAddress fromAddr = null;
InternetAddress[] toAddr = new InternetAddress[recipientArr.length];
for (int i = 0; i < recipientArr.length; i++) {
toAddr[i] = new InternetAddress(recipientArr[i]);
}
String nick = javax.mail.internet.MimeUtility.encodeText(name);
fromAddr = new InternetAddress(nick); // 邮件显示地址
message.setFrom(fromAddr); // 设置发送地址
message.setRecipients(Message.RecipientType.TO, toAddr); // 设置接收地址
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
message.setSubject(subject + "[" + df.format(new Date()) + "]"); // 设置邮件标题
message.setText(context); // 设置邮件正文
message.setSentDate(new Date()); // 设置邮件日期
message.saveChanges(); // 保存邮件更改信息
String mailSendEnable = ConfigProperty.getMail_send_enable();
if (mailSendEnable.equals("1")) {//开启发送功能
Transport transport = s.getTransport(transType);
transport.connect(host, address, password); // 服务器地址,邮箱账号,邮箱密码
transport.sendMessage(message, message.getAllRecipients()); // 发送邮件
transport.close();// 关闭
System.out.println("邮件发送成功");
} else {
System.out.println("邮件发送功能已经关闭");
}
} catch (Exception e) {
e.printStackTrace();
flag = false;// 发送失败
}
return flag;
}
public static void main(String[] args) {
SendMessage.sendMail("【系统提示】发送邮件成功通知", "测试内容", new String[]{"5165325@qq.com"});
}
}