Java

java如何实现定期发送邮件功能

小亿
128
2024-01-22 11:38:18
栏目: 编程语言

Java可以通过使用JavaMail API实现定期发送邮件的功能。下面是一个简单的示例代码:

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class EmailScheduler {
    private Timer timer;

    public EmailScheduler() {
        timer = new Timer();
    }

    public void scheduleEmail(String recipient, String subject, String message, Date date) {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 发送邮件
                sendEmail(recipient, subject, message);
            }
        }, date);
    }

    private void sendEmail(String recipient, String subject, String message) {
        String sender = "your-email@example.com"; // 发送者邮箱
        String password = "your-password"; // 发送者邮箱密码

        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.example.com"); // SMTP服务器地址
        props.setProperty("mail.smtp.auth", "true");

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(sender, password);
            }
        });

        try {
            // 创建邮件消息
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(sender));
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            mimeMessage.setSubject(subject);
            mimeMessage.setText(message);

            // 发送邮件
            Transport.send(mimeMessage);
            System.out.println("邮件已发送");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        EmailScheduler scheduler = new EmailScheduler();

        // 在指定日期时间发送邮件
        Calendar calendar = Calendar.getInstance();
        calendar.set(2022, Calendar.JANUARY, 1, 10, 0, 0);
        Date date = calendar.getTime();
        scheduler.scheduleEmail("recipient@example.com", "定期邮件", "这是一封定期发送的邮件", date);
    }
}

上述示例代码使用了java.util.Timer类来定时发送邮件。scheduleEmail方法可以指定要发送邮件的收件人、主题、内容以及发送的日期时间。通过sendEmail方法使用JavaMail API发送邮件。

请注意替换代码中的senderpasswordsmtp.example.com等信息为你自己的实际邮箱信息和SMTP服务器地址。

0
看了该问题的人还看了