<!-- email -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>
@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Mail {
private String subject;
private String message;
private Set<String> receivers;
}
import com.mmall.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;
@Slf4j
public class MailUtil {
public static boolean send(Mail mail) {
// TODO
String from = "";
int port = 25;
String host = "";
String pass = "";
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;
}
}
}
<!-- mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
spring:
mail:
host: 域 (比如qq的为smtp.qq.com;163的为smtp.163.com)
username: 邮箱
password: SMTP服务密码(非邮箱密码,可在邮件设置中设置)
properties:
mail:
smtp:
auth: true
import org.springframework.mail.javamail.JavaMailSender;
@Autowired
private JavaMailSender javaMailSender;
private void sendAlertMessage(String message){
SimpleMailMessage simpleMailMessage =new SimpleMailMessage();
simpleMailMessage.setFrom("");
simpleMailMessage.setTo("");
simpleMailMessage.setSubject("");
simpleMailMessage.setText(message);
javaMailSender.send(simpleMailMessage);
}