maven依赖
<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.2</version>
</dependency>
参考
Java 发送邮件 | 菜鸟教程
Java实现邮件发送_baolingye的博客-CSDN博客_java发送邮件
发送给多人
message.addRecipients(Message.RecipientType.CC,ccAddressList.toArray(new InternetAddress[ccAddressList.size()]));
示例代码
package cn.com.upxcy.springbootmybatis.utils;
import java.util.ArrayList;
import java.util.Properties;
import java.util.List;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSendUtil {
private static final String smtpHost = "";//smtp服务器地址
private static final String smtpPort = "";//smtp服务器地址
public static void sendMail(String title, String article, String fromAddress, String[] toAddress, String[] ccAddress) {
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", smtpHost);
properties.setProperty("mail.smtp.port", smtpPort);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MineMessage(session);
message.setSubject(title); //主题
message.setText(article); //内容
message.setFrom(new InternetAddress(fromAddress)); //发送方
List<InternetAddress> toAddressList = new ArrayList<>();
for (String addressStr : toAddressList) {
InternetAddress address = new InternetAddress(addressStr);
toAddressList.add(address);
}
message.addRecipients(Message.RecipientType.TO, toAddressList.toArray(new InternetAddress(toAddressList.size()))); //接收方
if (ccAddress != null) {
List<InternetAddress> ccAddressList = new ArrayList<>();
for (String addressStr : ccAddress) {
InternetAddress address = new InternetAddress(addressStr);
ccAddressList.add(address);
}
message.addRecipients(Message.RecipientType.CC, toAddressList.toArray(new InternetAddress(ccAddressList.size()))); //抄送方
//发送
Transport.send(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|