SpringBoot configure mail service :
1. introduction jar
<! - message ->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. Configure the resource file, mailbox parameters:
# Mail: Mail server spring.mail.host = smtp.163.com # sender's mailbox spring.mail.username = xxx @ 163.com # authorization code: spring.mail.password = abc123 # coding: spring.mail. encoding-default = UTF-. 8
3. Prepare to send mail method:
service layer reads the configuration file parameters, injection JavaMailSender
@Value ( "spring.mail.username $ {}" )
Private String SENDER ; // read parameter configuration file
@Autowired
Private JavaMailSender mailSender ; // automatically injected Bean
/ ** * Send plain text: * @param to the sender : * @param Subject sending Title : * @param context sending content : * / @Override public void sendSimpleMail (String to, String Subject, String context) { SimpleMailMessage the Message = new new SimpleMailMessage (); message.setFrom ( SENDER ); message.setTo (to); message.setSubject (Subject); message.setText (context); mailSender .send (Message); } / ** * send HTML: * @ param
to 发送人:
* @param subject 发送标题:
* @param context 发送内容:
*/
@Override
public void sendSimpleMailHTML(String to, String subject, String context) {
MimeMessage message = null;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sender);
helper.setTo(to);
helper.setSubject("Title: Send Html Content" );
the StringBuffer SB = new new the StringBuffer ();
sb.append ( "<h1 of> Title -H1 </ h1 of>" )
.append ( "<style = P 'Color: # F00 of'> in red </ P> " )
.append ( " <P style = 'text-align = left: right'> right alignment </ P> " );
helper.setText (sb.toString (), to true );
} the catch (Exception E) {
e.printStackTrace ();
}
mailSender .send (Message);
}