[英]Program for sending a message to email in Java
I created a program that sends files to email in Java.我创建了一个程序,将文件发送到 Java 中的 email。 How to insert a timer that will automatically send mail every 2 minutes?
如何插入一个每 2 分钟自动发送邮件的计时器? I think it could be through a timer, but if someone has a different way or encountered this or a similar problem, it would help me a lot.
我认为这可能是通过计时器,但如果有人有不同的方式或遇到这个或类似的问题,它会对我有很大帮助。
Here's the code:这是代码:
public class EMail {
public static void main(String[] args)
{
SendEmail();
}
private static void SendEmail ()
{
final String username = "youremail@gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("youremail@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("youremail@gmail.com"));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "C:\\Users\\Name\\UserData\\Logs.txt";
String fileName = "Logs.txt";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
You can use Timer
and TimerTask
which are java util classes used to schedule tasks in a background thread您可以使用
Timer
和TimerTask
,它们是 java 实用程序类,用于在后台线程中安排任务
Example (You can add this to main
method):示例(您可以将其添加到
main
方法):
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
SendEmail();
}
};
Timer timer = new Timer("MyTimer");
timer.scheduleAtFixedRate(timerTask, 500, 2000);
You can do something like this.This code will enable you to send mails for every two minutes.您可以这样做。此代码将使您能够每两分钟发送一次邮件。
public class EmailHandler{
public static void main(String[] args){
Thread emailSenderThread = new Thread(new EmailSender());
emailSenderThread.start();
}
private static class EmailSender implements Runnable {
private void sendEmail(){
//Email sending logic Impl
}
@Override
public void run() {
for(;;){
sendEmail();
try {
Thread.sleep(120000);//Thread is sleeping for 2 minutes
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.