One, the introduction

Recently, I saw an article about using JS code to express my feelings.

And then I realized that I could do it in Java code, and then I started writing code, and it was kind of fun, and I didn’t have to talk about it

Implementation idea:

  • Use HttpClient to remotely access the contents of the Rainbow Fart Generator website: chp.shadiao.app/
  • Java Mail implements Mail sending
  • SpringBoot integrates Scheduled implementation of mail delivery

Ii. Construction project

Project environment On the basis of SpringBoot framework, add a Maven project to send mail, RPC remote call httpClient, Scheduled, depending on the following:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.32..RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <! - httpclient dependence - > < the dependency > < groupId > org.. Apache httpcomponents < / groupId > < artifactId > httpclient < / artifactId > <version>4.512.</version> </dependency> </dependencies> <! <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <fork>true</fork>
            </configuration>
        </plugin>
    </plugins>
</build>
Copy the code

Write the configuration

Before compiling the configuration, log in to your mailbox in a browser and enable the POP3/SMTP service in account security

Start The POP3/SMTP service requires a verification code

Copy authorization code

Select SMTP to save the mail to the server, select this item mainly to see what information you sent, do not select this item. Email After the message is sent successfully, you cannot see the sent message in the mailbox

Write configurations based on authorization codes

Spring: mail: username: [email protected] email address password # oneself: # XXXXXXX SMTP | POP3 | the IMAP protocol authorization code host: smtp.qq.com # server address. Refer to the information provided by the mailbox service provider. properties: mail: smtp: auth:truePort:587She: Mail: xxxxxx@163.com
Copy the code

Four, write the SpringBoot boot class

@EnableScheduling
@SpringBootApplication
public class BiaoBaiApp {
    public static void main(String[] args) {
        SpringApplication.run(BiaoBaiApp.class,args);
}
Copy the code

5. Automatically generate sending content

@Component
public class SendMessage {
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;
    @Value("${she.mail}") private String[] sheMail; public void sendMessage(String subject,String message) { try { MimeMessage mimeMessage = mailSender.createMimeMessage();  MimeMessageHelper helper =new MimeMessageHelper(mimeMessage);
            helper.setFrom(from);// Sender email address
            helper.setTo(sheMail);// Recipient's mailbox
            helper.setSubject(subject);// Send the subject
            helper.setText(message);// Send the content
            mailSender.send(helper.getMimeMessage());// Send an email} catch (MessagingException e) { e.printStackTrace(); }}/** Get the message to be sent remotely */
    public static String getOneS(){
        try {
            // Create a client object
            HttpClient client = HttpClients.createDefault();
            / * create address https://du.shadiao.app/api.php * /
            HttpGet get = new HttpGet("https://chp.shadiao.app/api.php");
            // Initiates the request and receives the response object
            HttpResponse response = client.execute(get);
            // Get the body of the response, which is an object based on the HTTP protocol standard string
            // The response body and response header encapsulate HTTP data. If used directly, garbled characters or parsing errors may occur
            HttpEntity entity = response.getEntity();
            // Convert the response body data through the HTTP entity utility class
            String responseString = EntityUtils.toString(entity, "utf-8");

            return responseString;

        } catch (IOException e) {
            throw  new RuntimeException("Website failed to get sentence"); }}}Copy the code

Write a scheduled task

@Component
public class MyScheduled {
    @Autowired
    private SendMessage sendMessage;

    /* Perform the task at 5:20 every day */
    @Scheduled(cron ="0 20 17 * * *")
    public void dsrw(){
        String message = sendMessage.getOneS();
        sendMessage.sendMessage("News from tea and porridge! ❤",message); }}Copy the code

Seven, package operation

Conditional jar package can be placed on the transport server, there is no condition can be in the local Win10 system to add a scheduled task, a regular jar package every day.

Jar packages on the server need to permit port 587, firewall permit port 587

In addition to permit, there are also permit HTTP ports and HTTPS ports

Then start the JAR package in the background on Linux

Nohup Java -jar jar package >test.log &Copy the code

Win10 timed jar package in the task planner to create a task

Creating a new trigger

Create a new action, enter the jar command to execute in the program or script, and click OK

Then you can see that the task has been created

Eight, summary

The code still has a lot to improve and a lot to fall short of.

Due to time reasons, there are many places that can be optimized, such as: sending simple text content of the mail, not beautiful, you can realize the HTML way to send mail, so that the content of the mail is more beautiful.

public  void sendHtmlMessage(String subject,String message){
    try {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
        helper.setFrom(from);
        helper.setTo(sheMail);
        helper.setSubject(subject);
        helper.setText(message,true);//true Send in HTML modemailSender.send(helper.getMimeMessage()); } catch (MessagingException e) { e.printStackTrace(); }}Copy the code

Finally, the source code is attached for your reference:

Links:

Pan.baidu.com/s/1e9Iiy5om…

Extraction code: 26SS

From: blog.csdn.net/qq_33758782