相关步骤
- 配置发送邮件相关信息
# 邮件服务配置
mail:
host: smtp.qiye.aliyun.com
port: 465
username: 发送者对应的邮箱账号
password: 发送者对应的邮箱密码
to: 目标邮箱账号,多个账号之间用英文逗号隔开;例如xxx@dd.com,www@dd.com
- 编写邮箱发送服务
import com.oaker.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.Security;
import java.util.Properties;
@Component
@EnableScheduling //开启定时服务
public class MailServiceImpl {
private static final Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
@Value("${spring.mail.host}")
private String host;
@Value("${spring.mail.port}")
private String port;
@Value("${spring.mail.username}")
private String username;
@Value("${spring.mail.password}")
private String password;
@Value("${spring.mail.to}")
private String to;
@Scheduled(cron = "0 0 9 * * ? ") //每天上午九点发送邮件cron表达式具体用法可参考:https://blog.csdn.net/study_665/article/details/123506946
public void sendUseHourExcel() {
//设置SSL连接、邮件环境
try {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
//设置端口
props.setProperty("mail.smtp.port", port);
//启用调试
props.setProperty("mail.debug", "true");
props.setProperty("mail.smtp.socketFactory.port", port);
props.setProperty("mail.smtp.auth", "true");
//建立邮件会话
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
//建立邮件对象
MimeMessage message = new MimeMessage(session);
//设置邮件的发件人、收件人、主题
//发件人账号
message.setFrom(new InternetAddress(username));
//收件人账号
if (StringUtils.isEmpty(to)) {
return;
}
String[] targets = to.split(",");
Address[] addresses = new Address[targets.length];
for (int i = 0; i < targets.length; i++) {
addresses[i] = new InternetAddress(targets[i]);
}
message.setRecipients(Message.RecipientType.TO, addresses);
//邮件标题
message.setSubject("邮件标题");
//内容
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
//邮件内容
contentPart.setContent("您好,这是发送的邮件!", "text/html;charset=utf-8");
multipart.addBodyPart(contentPart);
message.setContent(multipart);
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
logger.info("发送邮箱失败:" + e.getMessage());
}
}
}
结语
如果以上文章对您有一点点帮助,希望您不要吝啬的点个赞加个关注,您每一次小小的举动都是我坚持写作的不懈动力!ღ( ´・ᴗ・` )