Using Java to realize the daily estrus words to the object

I. Introduction

I recently saw an article about confession using js code, and I was deeply moved.
Then I found that I could also use java code to implement it, and then I started to write the code. I found it was quite interesting, so I don’t want to talk about it.
Implementation idea:
Use HttpClient to remotely get the content of the rainbow fart generator website: https:// chp.shadiao.app/

java Mail realizes sending mail

SpringBoot integrates Scheduled to send emails regularly

Second, build the project

The project environment is based on the SpringBoot framework, adding a Maven project for sending mail, RPC remote calling httpclient, and Scheduled. The dependencies are as follows:

org.springframework.boot
spring-boot-starter-parent
2.3.2.RELEASE

    <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 依赖 -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.12</version>
    </dependency>
</dependencies>

<!--打包插件-->
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
            </configuration>
        </plugin>
    </plugins>
</build>

Three, write configuration

Before writing the configuration, you need to log in to your email in the browser and set the POP3/SMTP service in the account security to Insert picture description here
start the POP3/SMTP service. You need to enter the verification code to start the POP3/SMTP service. Insert picture description here
Copy the authorization code and Insert picture description here
check SMTP to send the letter and save it to the server, check this The item is mainly to see what information you have sent, so uncheck this item. After the email message is sent successfully, I cannot see the information I have sent in my mailbox. Insert picture description here
Write and configure the authorization code spring:
mail:
username: [email protected] # My email address
password: xxxxxxx # SMTP|POP3|IMAP protocol authorization code
host: smtp.qq.com # Server address. Refer to the information provided by the mailbox service operator.
properties:
mail:
smtp:
auth: true # Enable smtp protocol verification
port: 587

To whom

she:
mail: [email protected]

Fourth, write the SpringBoot startup class

@EnableScheduling
@SpringBootApplication
public class BiaoBaiApp { public static void main(String[] args) { SpringApplication.run(BiaoBaiApp.class,args); } 5. Automatically generate sending content



@Component
public class SendMessage {
@Autowired
private JavaMailSender mailSender;
@Value(" s p r i n g . m a i l . u s e r n a m e " ) p r i v a t e S t r i n g f r o m ; @ V a l u e ( " {spring.mail.username}") private String from; @Value(" spring.mail.username")privateStringfrom;@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);//发送者邮件邮箱
        helper.setTo(sheMail);//收邮件者邮箱
        helper.setSubject(subject);//发件主题
        helper.setText(message);//发件内容
        mailSender.send(helper.getMimeMessage());//发送邮件
    } catch (MessagingException e) {
        e.printStackTrace();
    }

}
/**远程获取要发送的信息*/
public static String getOneS(){
    try {
        //创建客户端对象
        HttpClient client = HttpClients.createDefault();
        /*创建地址 https://du.shadiao.app/api.php*/
        HttpGet get = new HttpGet("https://chp.shadiao.app/api.php");
        //发起请求,接收响应对象
        HttpResponse response = client.execute(get);
        //获取响应体,响应数据是一种基于HTTP协议标准字符串的对象
        //响应体和响应头,都是封装HTTP协议数据。直接使用可能出现乱码或解析错误
        HttpEntity entity = response.getEntity();
        //通过HTTP实体工具类,转换响应体数据
        String responseString = EntityUtils.toString(entity, "utf-8");

        return responseString;

    } catch (IOException e) {
        throw  new RuntimeException("网站获取句子失败");
    }
}

}

Six, write timed tasks

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

/*定时执行任务方法 每天5点20执行该任务*/
@Scheduled(cron ="0 20 17 * * *")
public void dsrw(){
    String message = sendMessage.getOneS();
    sendMessage.sendMessage("来自清茶淡粥的消息!❤",message);
}

}
Seven, package and run

If you have conditions, you can put the jar package on the shipping server. If there are no conditions, you can add a scheduled task on the local win10 system and execute the jar package regularly every day.
The jar package needs to be released on the server port: 587, the firewall releases the 587 port.
In addition to the release, there are also http and https ports to be released. Insert picture description here
Then start the jar package
nohup java -jar jar package>test.log &
win10 on the linux background. Create a task in the task scheduler, create a Insert picture description here
new trigger, Insert picture description here
create a new operation, enter the executed jar command in the program or script, click OK, Insert picture description here
and then you can see the created task. Insert picture description here
8. Summary

The code has been greatly improved, and there are many shortcomings.
Due to time reasons, there are still many areas that can be optimized. For example, sending mails with pure text content is not beautiful. You can send mails in html mode to make the content of sent mails 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 Use html to send mailSender.send(helper.getMimeMessage()); } catch (MessagingException e) { e.printStackTrace(); } There are many shortcomings in the editor Office, everyone is welcome to leave a message in the comment area to discuss











Guess you like

Origin blog.csdn.net/dcj19980805/article/details/114880657