springboot mail 发送邮件

新开发了一个新的功能,要求使用java发送邮件,在此记录下代码,以方便后来者:

1、首先需要开通邮箱,开通smtp功能,我这边使用的是新浪邮箱,试过163、qq,比较麻烦,后来看到别人使用新浪,直接使用了新浪邮箱。(具体开通方式不在些细述)

2、在pom.xml中添加如此依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

3、在application.yml处添加如下配置

mail:
host: smtp.sina.com
port: 25
username:xx@sina.com #此处为邮箱帐号
password: xxx #此处为smtp授权码,一般会和密码相同
properties:
mail:
smtp:
auth: true
timeout: 25000

4、添加配置类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class EmailConfig {
/**
* 发件邮箱
*/
@Value("${spring.mail.username}")
private String emailFrom;

public String getEmailFrom() {
return emailFrom;
}

public void setEmailFrom(String emailFrom) {
this.emailFrom = emailFrom;
}
}

5、以下是发送方法

@Autowired
private EmailConfig emailConfig; //注入配置文件

public boolean sendAttachmentsMail(String[] to, String[] copyTo, String subject, String content, String filePath) {
boolean flag = false;
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(emailConfig.getEmailFrom());
helper.setTo(to); //to为收件人,此处为数组,可支持发送给多人
helper.setCc(copyTo); //copyTo为抄送人,此处为数组,可支持发送给多人
helper.setSubject(subject); //subject为主题
helper.setText(content, true); //content为内容
if (null != filePath) {
FileSystemResource file = new FileSystemResource(new File(filePath));
helper.addAttachment(filePath, file); //此处为附件,可添加附件发送
}
message.setSentDate(new Date()); //发送时间
mailSender.send(message); //发送
flag = true;
} catch (MessagingException e) {
e.printStackTrace();
}
return flag;
}
  
原文地址:https://www.cnblogs.com/linhuchong1/p/9528959.html