Spring Boot mail function

1. scenario

Application scenarios mail function can be described as very broad, such as user registration, password recovery, message notification, as well as some abnormality notification procedures and so need to use this feature.

It is because of the widespread use of e-mail function, so springboot also add a message added in its assembly.

 

2.maven dependence

springboot has given us ready for the relevant components of the message, as long as we in the springboot add it to the project.

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

After addition of the component related to continue to view dependency (below), which can be seen the package is actually javax.mail mailer related classes.

 

3. Send regular mail

We start by writing a simple text sample e-mail, to be followed then sent several other complex messages, and parsing source code on the part of the demo examples.

3.1. Configuration File

# I am here to send mail using QQ mailbox, so the configuration of the host is smtp.qq.com, use another mailbox need to find the corresponding host 
spring.mail.host = smtp.qq.com 
#-mail account to send mail 
spring.mail. username=*********@qq.com 
# send mail mailbox SMTP service password (some mail using the mail password, a different mailbox may vary) 
spring.mail.password = ***** ***** 
# whether to authenticate 
spring.mail.properties.mail.smtp.auth = to true 
spring.mail.properties.mail.smtp.starttls.enable = to true 
spring.mail.properties.mail.smtp.starttls. required = true

3.2 Usage

@Component 
public class EmailService { 

    @Autowired 
    Private JavaMailSender mailSender; 

    public void SendMsg () { 
        SimpleMailMessage MailMessage = new new SimpleMailMessage (); 
        // sender of the message, not just here to fill in, must be true to send mail mailbox name 
        mailMessage.setFrom ( "[email protected]"); 
        // e-mail recipients 
        mailMessage.setTo ( "[email protected]"); 
        // message subject 
        mailMessage.setSubject ( "testSubject"); 
        // message content 
        mailMessage.setText ( "hello email ");! 
        // send mail 
        mailSender.send (MailMessage); 
    } 

}

3.3 test code

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Autowired
    private EmailService emailService;

    @Test
    public void contextLoads() {
        emailService.sendMsg();
    }

}

3.4 Check-mail

 

4. complex messages sent

Complex messages into a variety of situations, due to limited space, here only briefly enumerate several of.

4.1 multiple e-mail recipients

We view the above method set setTo () Source:

    public void setTo(String to) {
        this.to = new String[]{to};
    }

    public void setTo(String... to) {
        this.to = to;
    }

Visible inside is actually our argument passed as an array to accept, so we can send messages to multiple recipients in the following two forms:

  1. Array.
  2. Multiple parameters.
        // 邮件接受者
        mailMessage.setTo("","","");
        mailMessage.setTo(new String[]{"",""});

4.2 cc

Add Cc recipients by adding similar manner, except that the method name, Add Cc's approach to setCc ():

    public void setCc(String cc) {
        this.cc = new String[]{cc};
    }

    public void setCc(String... cc) {
        this.cc = cc;
    }

The same can also add one or more Cc by adding an array form and a plurality of parameters:

        // 邮件抄送者
        mailMessage.setCc("");
        mailMessage.setCc("","");
        mailMessage.setCc(new String[]{"",""});

4.3 Sending messages with path

Complex than a simple e-mail messages, message classes used here is no longer SimpleMailMessage. But generated by the mailer JavaMailSender MimeMessage as a message-based, to be simultaneously add a helper class MimeMessageHelper message.

    void sendComplexMsg public () { 
        the MimeMessage = mailSender.createMimeMessage Message (); 

        the try { 
// message generating auxiliary class, attention is later used to determine whether to add true attachment MimeMessageHelper MessageHelper = new new MimeMessageHelper (Message, true); messageHelper.setSubject ( "testSubject"); messageHelper.setFrom ( "[email protected]"); messageHelper.setTo ( "[email protected]");
// true back here, to make text content for display in html format, if is not provided, the inside links are as ordinary strings show messageHelper.setText ( "
< a the href = \" # \ "> link </a>", to true); } the catch (MessagingException E) { e.printStackTrace () ; } mailSender.send(message); }

4.4 add an attachment

Add attachment and add content with a path similar, the only difference is that more use of "addAttachment ()" method. Methods The first parameter is named attachment in the message, and the second parameter is the file to be uploaded.

A message can add multiple attachments, as long as continue to call addAttachment () method can be.

But it notes that when sending file attachments, setText () must be called, otherwise the program will throw an exception, can not send mail.

    public void sendComplexMsg() {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setSubject("testSubject");
            messageHelper.setFrom("[email protected]");
            messageHelper.setTo("[email protected]");
            messageHelper.setText("<a href=\"#\">链接</a>", true);
            messageHelper.addAttachment("附件", new File("D://yxf//123.txt"));
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        mailSender.send(message);

    }

4.5

 

Guess you like

Origin www.cnblogs.com/yxth/p/11202837.html