SpringBoot Mail

Spring Boot integrated mail service could be so simple, quick to grasp the core logic and corporate e-mail messages daily business class service.

What is SMTP?

Called the SMTP Simple Mail Transfer Protocol (Simple Mail Transfer Protocol), which is from a set of source to destination message transfer standard, which controls the relay by way of the message. SMTP authentication is required to provide account and password to login to the server, it is designed to prevent users from being against spam.

What is IMAP?

IMAP called the Internet Message Access Protocol (Internet Mail Access Protocol), IMAP allows getting mail from the mail server information, download mail. IMAP and POP similar, is a mail acquisition agreement.

What is POP3?

POP3 called the Post Office Protocol 3 (Post Office Protocol), POP3 client support for remote management server-side mail. POP3 commonly used in the "offline" mail processing, which allows the client to download e-mail server, then the mail on the server will be deleted. At present, many POP3 mail server download only the mail function, do not delete the mail server itself, which belongs to the improved version of the POP3 protocol.

IMAP and POP3 protocols What difference will it make?

Biggest difference is that, the IMAP allows bidirectional communication, the client will be fed back to the operation of the server, for example, receive mail client, marking as read operations, the server will follow synchronize these operations. For POP protocol although it allows the client to download e-mail server, but the client's operations and are not synchronized to the server above, for example, charge a mark or read messages on the client, the server does not synchronize these operations.

What is JavaMailSender and JavaMailSenderImpl ?

JavaMailSender and JavaMailSenderImpl is the interface and implementation classes Spring integration provided by the official mail service, a simple and efficient design is known, is now the mainstream Java back-end tool to send e-mail and integrated mail service.

How JavaMailSenderImpl send mail?

Very simple, direct injection in business class JavaMailSenderImpl and calls the send method to send the message. Wherein Simple Mail can SimpleMailMessage to send messages, and complex messages (e.g. add attachments) can use MimeMessageHelper be constructed MimeMessage send mail. E.g:

@Autowired

    private JavaMailSenderImpl mailSender;

 

    public void sendMail() throws MessagingException {

        

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

        simpleMailMessage.setFrom("[email protected]");

        simpleMailMessage.setTo("[email protected]");

        simpleMailMessage.setSubject("Happy New Year");

        simpleMailMessage.setText("新年快乐!");

        mailSender.send(simpleMailMessage);

 

        

        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);

        messageHelper.setFrom("[email protected]");

        messageHelper.setTo("[email protected]");

        messageHelper.setSubject("Happy New Year");

        messageHelper.setText("新年快乐!");

        messageHelper.addInline("doge.gif", new File("xx/xx/doge.gif"));

        messageHelper.addAttachment("work.docx", new File("xx/xx/work.docx"));

        mailSender.send(mimeMessage);

    }

 

  

 

Why JavaMailSenderImpl can out of the box?

The so-called out-of-fact, based on official built-in automatic configuration, look at its source code can be automatically configured message class (MailSenderPropertiesConfiguration) provides the context for the mail service instance (JavaMailSenderImpl) . Specific source as follows:

@Configuration

@ConditionalOnProperty(prefix = "spring.mail", name = "host")

class MailSenderPropertiesConfiguration {

    private final MailProperties properties;

    MailSenderPropertiesConfiguration(MailProperties properties) {

        this.properties = properties;

    }

    @Bean

    @ConditionalOnMissingBean

    public JavaMailSenderImpl mailSender() {

        JavaMailSenderImpl sender = new JavaMailSenderImpl();

        applyProperties(sender);

        return sender;

    }

  

 

Which MailProperties configuration information about the mail server, the specific source code as follows:

@ConfigurationProperties(prefix = "spring.mail")

public class MailProperties {

    private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    private String host;

    private Integer port;

    private String username;

    private String password;

    private String protocol = "smtp";

    private Charset defaultEncoding = DEFAULT_CHARSET;

    private Map<String, String> properties = new HashMap<>();

}

  

 

First, open the e-mail service

Landing NetEase mailbox 163, in open settings and check the POP3 / SMTP / IMAP service, and then get an authorization code, authorization code and the mailbox will be used for login authentication.

 

Second, configure mail service

First we by creating a project the send-mail the Spring-springboot Initializr , as shown:

 

Then pom.xml introduced web, thymeleaf and spring-boot-starter-mail related dependency. E.g:

<dependencies>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-thymeleaf</artifactId>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-mail</artifactId>

        </dependency>

        <dependency>

            <groupId>org.webjars</groupId>

            <artifactId>webjars-locator-core</artifactId>

        </dependency>

        <dependency>

            <groupId>org.webjars</groupId>

            <artifactId>jquery</artifactId>

            <version>3.3.1</version>

        </dependency>

        <dependency>

            <groupId>org.webjars</groupId>

            <artifactId>bootstrap</artifactId>

            <version>3.3.7</version>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-devtools</artifactId>

            <scope>runtime</scope>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

            <scope>test</scope>

        </dependency>

    </dependencies>

  

According to the aforementioned configuration items (MailProperties) fill in the relevant configuration information, spring.mail.username indicates authentication when connecting to the mail server login account may be a normal mobile phone number or login ID, not necessarily the mailbox, in order to solve this problem , I recommend the spring.mail. properties.from fill in the e-mail sender mailbox that is true.

Then application.yml add the following configuration:

 

the Spring: 

  mail: 

    Host: smtp.163.com #smtp server address 

    username: socks # login account 

    password: 123456 # login password (or authorization code) 

    the Properties: 

      from: [email protected] #-mail sender (ie real mailbox) 

  Thymeleaf: 

    Cache: to false 

    prefix: CLASSPATH: / views / 

  the servlet: 

    multipart: 

      max-file-size: # 10MB file size limits of a single 

      max-request-size: 50MB # total restriction request

 

  

Through the front of the advanced knowledge, we know that before sending the message, you need to build  SimpleMailMessage or  MimeMessage mail message classes to fill in the message header, message content and other information, and finally submitted to JavaMailSenderImpl send a message, so it looks no problem, but also to achieve stated objectives, but there will be a large number of fragmented and duplicated code in actual use, not easy to save messages to the database.

So elegant outgoing mail should be about? You should block out the details of construction information and send messages, whether simple or complex messages can be unified to send mail API. For example: mailService.send (mailVo).

For example, by mail informational message subject when sending mail to save (MailVo), message content and other information:

package com.hehe.vo;

 

public class MailVo {

    private String id;

    private String from;

    private String to;

    private String subject;

    private String text;

    private Date sentDate;

    private String cc;

    private String bcc;

    private String status;

    private String error;

    @JsonIgnore

    private MultipartFile[] multipartFiles;

   

}

  

Third, send messages and attachments

In addition to sending e-mail, mail and further comprising detecting operations such as saving messages, for example:

  • Detection Mail  checkMail (); First, check e-mail recipient, the message subject and content of these messages required, if it is empty then refused to send.
  • Send Mail  sendMimeMail (); followed by MimeMessageHelper to resolve and build MailVo MimeMessage transfer messages.
  • Save Mail  sendMimeMail (); Finally, save the message to the database for statistical and tracing mail problems.

In this case the mail business class  MailService specific source code as follows:

package com.hehe.service;

 

 

@Service

public class MailService {

 

    private Logger logger = LoggerFactory.getLogger(getClass());

 

    @Autowired

    private JavaMailSenderImpl mailSender;

 

 

    

    public MailVo sendMail(MailVo mailVo) {

        try {

            checkMail(mailVo);

            sendMimeMail(mailVo);

            return saveMail(mailVo);

        } catch (Exception e) {

            logger.error("发送邮件失败:", e);

            mailVo.setStatus("fail");

            mailVo.setError(e.getMessage());

            return mailVo;

        }

 

    }

 

    

    private void checkMail(MailVo mailVo) {

        IF (StringUtils.isEmpty (mailVo.getTo ())) { 

            the throw a RuntimeException new new ( "message can not be empty recipient"); 

        } 

        IF (StringUtils.isEmpty (mailVo.getSubject ())) { 

            the throw a RuntimeException new new ( "message subject can not be empty "); 

        } 

        IF (StringUtils.isEmpty (mailVo.getText ())) { 

            the throw a RuntimeException new new (" message can not be empty "); 

        } 

    } 

 

    

    Private void sendMimeMail (mailVo mailVo) { 

        the try { 

            MimeMessageHelper = new new MessageHelper MimeMessageHelper (mailSender.createMimeMessage (), to true); 

            mailVo.setFrom (getMailSendFrom ()); 

            messageHelper.setFrom (mailVo.getFrom ());

            messageHelper.setTo(mailVo.getTo().split(","));

            messageHelper.setSubject(mailVo.getSubject());

            messageHelper.setText(mailVo.getText());

            if (!StringUtils.isEmpty(mailVo.getCc())) {

                messageHelper.setCc(mailVo.getCc().split(","));

            }

            if (!StringUtils.isEmpty(mailVo.getBcc())) {

                messageHelper.setCc(mailVo.getBcc().split(","));

            }

            if (mailVo.getMultipartFiles() != null) {

                for (MultipartFile multipartFile : mailVo.getMultipartFiles()) {

                    messageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile);

                }

            }

            if (StringUtils.isEmpty(mailVo.getSentDate())) {

                mailVo.setSentDate(new Date());

                messageHelper.setSentDate(mailVo.getSentDate());

            }

            mailSender.send(messageHelper.getMimeMessage());

            mailVo.setStatus("ok");

            logger.info("发送邮件成功:{}->{}", mailVo.getFrom(), mailVo.getTo());

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

 

    

    private MailVo saveMail(MailVo mailVo) {

        

        return mailVo;

    }

 

    

    public String getMailSendFrom() {

        return mailSender.getJavaMailProperties().getProperty("from");

    }

}

  

 

Send e-mail to get the core business logic, then we write a simple page to send mail.

First written controller to interact with the page  MailController , specific source code as follows:

@RestController

public class MailController {

    @Autowired

    private MailService mailService;

 

    

    @GetMapping("/")

    public ModelAndView index() {

        ModelAndView mv = new ModelAndView("mail/sendMail");

        mv.addObject("from", mailService.getMailSendFrom());

        return mv;

    }

    

    @PostMapping("/mail/send")

    public MailVo sendMail(MailVo mailVo, MultipartFile[] files) {

        mailVo.setMultipartFiles(files);

        return mailService.sendMail(mailVo);

    }

}

  

 

Then / resources / views / mail directory create sendMail.html , specific source as follows:

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

 

<head>

    <meta charset="UTF-8"/>

    <title>发送邮件</title>

    <link th:href="@{/webjars/bootstrap/css/bootstrap.min.css}" rel="stylesheet" type="text/css"/>

    <script th:src="@{/webjars/jquery/jquery.min.js}"></script>

    <script th:href="@{/webjars/bootstrap/js/bootstrap.min.js}"></script>

 

</head>

 

<body>

<div class="col-md-6" style="margin:20px;padding:20px;border: #E0E0E0 1px solid;">

    <marquee behavior="alternate" onfinish="alert(12)" id="mq"
             onMouseOver = "this.stop ();. $ ( '# Egg') text ( 'to have a skill Let me go ah ');! ">

             ah really listen!');"onMouseOut = "this.start ();.


        <h5 id="egg">祝大家新年快乐!</h5><img id="doge" src="http://pics.sc.chinaz.com/Files/pic/faces/3709/7.gif" alt="">

    </marquee>

 

    <form class="form-horizontal" id="mailForm">

        <div class="form-group">

            <label class="col-md-2 control-label">邮件发信人:</label>

            <div class="col-md-6">

                <input class="form-control" id="from" name="from" th:value="${from}" readonly="readonly">

            </div>

        </div>

        <div class="form-group">

            <label class = "col-md- 2 control-label"> message recipient: </ label> 
                <INPUT class = "form-Control" ID = "to" name = "to" title = "multiple mailboxes to use, separated by">

            <div class = ". 6-COL-MD">


            </div>

        </div>

        <div class="form-group">

            <label class="col-md-2 control-label">邮件主题:</label>

            <div class="col-md-6">

                <input class="form-control" id="subject" name="subject">

            </div>

        </div>

        <div class="form-group">

            <label class="col-md-2 control-label">邮件内容:</label>

            <div class="col-md-6">

                <textarea class="form-control" id="text" name="text" rows="5"></textarea>

            </div>

        </div>

        <div class="form-group">

            <label class="col-md-2 control-label">邮件附件:</label>

            <div class="col-md-6">

                <input class="form-control" id="files" name="files" type="file" multiple="multiple">

            </div>

        </div>

        <div class="form-group">

            <label class="col-md-2 control-label">邮件操作:</label>

            <div class="col-md-3">

                <a class="form-control btn btn-primary" onclick="sendMail()">发送邮件</a>

            </div>

            <div class="col-md-3">

                <a class="form-control btn btn-default" onclick="clearForm()">清空</a>

            </div>

        </div>

    </form>

 

    <script th:inline="javascript">

        appCtx = var [[$ # request.getContextPath {()}]]; 

 

        function the sendMail () { 

 

            var formData the FormData new new = ($ ( '# Mailform') [0]); 

            $ .ajax ({ 

                URL: appCtx + ' / mail / the send ', 

                of the type: "POST", 

                the Data: formData, 

                contentType: false, 

                processData: false, 

                success: function (the Result) { 

                    Alert (result.status ===' the ok '' sent successfully! ":?" you are the Doge sarcasm: "+ result.error); 

                }, 

                error: function () { 

                    Alert ("! transmission failure "); 

                } 

            });

        }

 

        function clearForm() {

            $('#mailForm')[0].reset();

        }

 

        setInterval(function () {

            var total = $('#mq').width();

            var width = $('#doge').width();

            var left = $('#doge').offset().left;

            if (left <= width / 2 + 20) {

                $('#doge').css('transform', 'rotateY(180deg)')

            }

            if (left >= total - width / 2 - 40) {

                $('#doge').css('transform', 'rotateY(-360deg)')

            }

        });

    </script>

</div>

</body>

</html>

  

 

Fourth, test sending mail

If you are a beginner, it is recommended that you first download the source code, modify the configuration after running the project, after the success of their own to re-write the code again, which helps to enhance memory. This number can get the source code public " Java back-end" backstage reply e-mail acquisition.

Start the project and access: HTTP: // localhost: 8080 and then send the message you can see the main interface as follows:

 

Then fill your mailbox trumpet, click to send a message, if successful can visit trumpet mailbox and view messages just upload attachments.

 

At this point Send e-mail to complete all the code, welcome to download and follow Github source.

Fifth, the common encoding failed

If the company customized mail server, mail log records naturally, according to the error code is stored log favor of routine maintenance.

For example, these error codes provided by NetEase mailbox identification:

421

421 HL: REP send the IP abnormal behavior, the presence of absence of a large number of the recipient, the connection is temporarily prohibited. Please check for users to send viruses or spam, and send a check list of validity;

421 HL: ICC The IP concurrent connections is too large, exceeding the limit of Netease, it is temporarily prohibited connection. Please check for users to send viruses or spam, and reduces the number of IP concurrent connections;

421 HL: IFC sent to the IP short period a large number of letters, netease exceeds the limit, the connection is temporarily prohibited. Please check for users to send viruses or spam, and lower the transmission frequency;

421 HL: MEP to send the IP abnormal behavior, there is a large number of domain names in counterfeit send behavior, the connection is temporarily prohibited. Please check for users to send viruses or spam, and send real and effective use of the domain name;

450

450 MI: Too many errors occur instruction CEL sender. Check the letter program;

450 MI: DMC currently connected number of messages sent exceeds the limit. Reduce the number of messages per connection in delivery;

450 MI: CCL sender sends the number of instructions beyond the normal. Check the letter program;

450 RP: DRC transmission connected to the current number of recipients exceeds the limit. Please control the number of messages delivered per connection;

450 RP: CCL sender sends the number of instructions beyond the normal. Check the letter program;

450 DT: RBL transmission in one or more IP in RBL. Please refer to http://www.rbls.org/ relevant information about the RBL;

450 WM: BLI YORK not allow the IP address of the transmission list;

450 WM: BLU netease this user is not allowed user list in the transmission;

451

451 DT: SPM, please try again with a message body to send spam features or lack of normative environment, it is temporarily rejected. Keep the mail queue, two minutes after the re-vote messages. Message content should be adjusted or optimized transmission environment;

451 Requested mail action not taken: too much fail authentication login failures too, was temporarily banned from. Please check the password and account verification settings;

451 RP: Too many errors instruction CEL sender appears. Check the letter program;

451 MI: DMC currently connected number of messages sent exceeds the limit. Please control the number of messages delivered per connection;

451 MI: Number of transmission SFQ sender within 15 minutes more than the limit, to control the transmission frequency;

451 RP: the cumulative number of recipients QRC originator short term exceeds the limit, the sender is temporarily prohibited letter. Please lower the transmission frequency to the user;

451 Requested action aborted: local error in processing system temporarily fails, try sending it again later;

500

500 Error: smtp command bad syntaxU sent a syntax error;

550 MI: NHD HELO command NOT NULL;

550 MI: IMF sender mail address irregularities. Please refer to the definition of e-mail http://www.rfc-editor.org/ norms;

550 MI: SPF sender IP is not the sending domain's SPF license. Please refer to http://www.openspf.org/ definition of SPF specification;

550 MI: DMA transmission of the message has not been licensed DMARC domain. Refer to the definition of http://dmarc.org/ DMARC specification;

550 MI: STC number of connections exceeds the number of the sender defining the day, the day no longer acceptable senders. Please control connection times;

550 RP: FRL NetEase mailbox does not open anonymous forwarding (Open relay);

550 RP: RCL mass number of recipients exceeded the limit, reduce the number of recipients per message;

550 RP: the cumulative number of recipients within the same day TRC sender exceeds the limit, the same day no longer accept the sender's message. Please lower the transmission frequency to the user;

550 DT: SPM message body with a lot of junk mail feature or send an environment lacking the normative. Message content should be adjusted or optimized transmission environment;

550 Invalid User request user does not exist;

550 User in blacklist the user is not allowed to transmit user YORK;

550 User suspended user request is disabled or frozen state;

550 Requested mail action not taken: too much recipient exceeds the number of mass limit;

552

552 Illegal Attachment not allowed to send this type of attachment, including .uu .pif .scr .mim .hqx .bhx .cmd .vbs .bat .com .vbe .vb .js .wsh like attachment end;

552 Requested mail action aborted: exceeded mailsize limit the size of letters transmitted exceeds the maximum allowed limit YORK mail received;

553

553 Requested action not taken: NULL sender is not allowed is not allowed sender is empty, please send using real sender;

553 Requested action not taken: Local user only SMTP type of machine is only allowed senders site users;

553 Requested action not taken: no smtp MX only MX type of machine is not allowed senders site users;

553 authentication is required SMTP requires authentication, check client settings;

554

554 DT: SPM sending the message content contains information not permitted, or system identified as spam. Please check for users to send viruses or spam;

554 DT: SUM envelope sender and the sender does not match the header;

554 IP is rejected, smtp auth error limit exceed the IP validation fails too many times, the connection is temporarily prohibited. Please check the verification information set;

554 HL: IHU letter IP because there is a connection to send spam or abnormal behavior, is temporarily suspended. Please detection and signaling IP signaling case letters in the history of the program whether or not there is an abnormality;

554 HL: IPB YORK not allow the IP address of the transmission list;

554 MI: within the same day cumulative limit the number of messages exceeds the STC Sender, the same day no longer accept the sender's Investment Trust. Please reduce the transmission frequency;

554 MI: SPB Netease this user is not allowed user list in the letter;

554 IP in blacklist that IP is not allowed to send Netease address list.

 

Guess you like

Origin www.cnblogs.com/Koaler/p/12381580.html