用Java写一个定时发送邮件的方法
时间: 2024-05-13 14:21:16 浏览: 211
非常好的问题,可以使用JavaMail API实现定时发送邮件的功能。以下是一个简单的示例代码:
```java
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.util.Timer;
public class MailSender {
public static void main(String args[]) {
Timer timer = new Timer();
timer.schedule(new MailTask(), 0, 1000 * 60 * 60 * 24); // 每隔一天发送一次邮件
}
}
class MailTask extends TimerTask {
public void run() {
Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("yourEmail@gmail.com", "yourEmailPassword");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("yourEmail@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipientEmail@gmail.com"));
message.setSubject("Subject");
message.setText("Message Content");
Transport.send(message);
System.out.println("Mail Sent");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
```
您需要在代码中替换您自己的电子邮件地址和密码,并在`MailTask`类的`run`方法中指定您要发送到的收件人电子邮件地址。这个示例代码将每隔一天发送一次邮件。
阅读全文