引入依赖
邮件实体类
可用邮件服务器地址(网易为例)
邮件工具类
import com.me.beans.Mail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import java.util.HashSet;
import java.util.Set;
@Slf4j
public class MailUtil {
public static boolean send(Mail mail) {
// 发送者邮箱
String from = "@163.com";
// 发送者授权码(第三方客户端时用密码会报550 User has no permission这样的错误,需要去授权)
String pass = "";
// 邮件服务器端口
int port = 25; // SMTP服务器
// 邮件服务器地址
String host = "smtp.163.com";
// 昵称
String nickname = "";
HtmlEmail email = new HtmlEmail();
try {
email.setHostName(host);
email.setCharset("UTF-8");
for (String str : mail.getReceivers()) {
email.addTo(str);
}
email.setFrom(from, nickname);
email.setSmtpPort(port);
email.setAuthentication(from, pass);
email.setSubject(mail.getSubject());
email.setMsg(mail.getMessage());
email.send();
log.info("{} 发送邮件到 {}", from, StringUtils.join(mail.getReceivers(), ","));
return true;
} catch (EmailException e) {
log.error(from + "发送邮件到" + StringUtils.join(mail.getReceivers(), ",") + "失败", e);
return false;
}
}
public static void main(String[] args) {
Set<String> receivers = new HashSet<>();
receivers.add("@qq.com");
Mail mail = Mail.builder().subject("测试邮件").message("测试信息").receivers(receivers).build();
send(mail);
}
}