java周期发送邮件代码
时间: 2023-10-31 21:11:30 浏览: 93
好的,以下是Java周期发送邮件的代码实现:
```java
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Timer;
import java.util.TimerTask;
public class EmailSender {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new EmailTask(), 0, 24 * 60 * 60 * 1000); //周期为1天,单位为ms,可根据需求调整
}
static class EmailTask extends TimerTask {
public void run() {
String fromEmail = "your_email_address";
String password = "your_email_password";
String toEmail = "recipient_email_address";
String subject = "Test Email";
String messageContent = "This is a test email.";
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
Session session = Session.getInstance(properties,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromEmail));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toEmail));
message.setSubject(subject);
message.setText(messageContent);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
System.out.println("Email sent successfully.");
}
}
}
```
希望能帮到你!现在轮到你来问问题了,请问有什么需要帮助的吗?
阅读全文