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發送郵件。
請注意替換代碼中的sender
、password
和smtp.example.com
等信息為你自己的實際郵箱信息和SMTP服務器地址。