A new feature has been developed that requires the use of Java to send mail, where the code is recorded to facilitate later:
1, the first need to open the mailbox, the SMTP function, I am using Sina mailbox, tried 163, QQ, more trouble, later saw others use Sina, direct use of Sina mailbox. (Specific opening method is not described in detail)
2. Add so dependent in Pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3, add the following configuration at Application.yml Place
mail:
host: smtp.sina.com
port: 25
username:[email protected] #此处为邮箱帐号
password: xxx #此处为smtp授权码,一般会和密码相同
properties:
mail:
smtp:
auth: true
timeout: 25000
4. Adding Configuration Classes
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, the following is the method of transmission
@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 is a recipient, and here is an array that can support sending to multiple people
HELPER.SETCC (CopyTo); CopyTo is a CC, here is an array that supports sending to multiple people
Helper.setsubject (subject); Subject as the theme
Helper.settext (content, true); Contents as Content
if (null! = FilePath) {
Filesystemresource file = new Filesystemresource (new file (FilePath));
Helper.addattachment (FilePath, file); Here is an attachment, you can add an attachment to send
}
Message.setsentdate (New Date ()); Send Time
Mailsender.send (message); Send
Flag = true;
} catch (Messagingexception e) {
E.printstacktrace ();
}
return flag;
}
Springboot Mail Send Message