1. 程式人生 > >springboot mail 發送郵件

springboot mail 發送郵件

return help rac 記錄 artifact sina host wired ets

新開發了一個新的功能,要求使用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:[email protected] #此處為郵箱帳號
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;
}

  

springboot mail 發送郵件