How to implement the function of sending emails regularly in Java?
Java can be used to implement the function of sending emails regularly through the use of the JavaMail API. Here is a simple example code:
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);
}
}
The above example code utilizes the java.util.Timer class to send emails at regular intervals. The scheduleEmail method allows you to specify the recipient, subject, content, and date/time for sending the email. The sendEmail method is used to send the email using the JavaMail API.
Please replace the sender, password, and smtp.example.com information in the code with your actual email information and SMTP server address.