检查条件并使用Java发送邮件

时间:2019-02-12 07:54:03

标签: java javamail

我需要通过

用Java发送邮件
  1. 检查文件夹
  2. 如果该文件夹中没有文件
  3. 发送邮件说文件夹为空

我尝试过使用时间表发送邮件的代码,每2秒发送一次邮件,并在2秒后停止发送邮件,但是我不知道如何检查情况 我有三类邮件发件人,主要任务和计划任务

任何人都可以帮忙吗?

提前谢谢!!!!

MailSender.java

public class MailSender {

    public static void send(String string, String messageString, String msgSubject) throws Exception {

      // Sender's email ID needs to be mentioned
      String from = "xyz@xyz.com";

      // Assuming you are sending email from localhost
      String host = "localhost";

      String port = "25";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server
      properties.setProperty("mail.smtp.host", host);
      properties.setProperty("mail.smtp.port", port);      

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(string));

         // Set Subject: header field
         message.setSubject(msgSubject);

         // Create the message part 
         BodyPart messageBodyPart = new MimeBodyPart();

         // Fill the message
         messageBodyPart.setText(messageString);
         messageBodyPart.setFileName("xyz.png");

         // Create a multi-part message
         Multipart multipart = new MimeMultipart();

         // Set text message part
         multipart.addBodyPart(messageBodyPart);
         message.setContent(messageString, "text/html; charset=utf-8");

        MimeMessage message1 = new MimeMessage(session);
        message1.setContent
        ("<h1>This is a test</h1>" 
         + "</images/zyx.png\">", 
         "text/html");

         // Send message
         Transport.send(message);
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }

MainClass.java

public class MainClass {
    public static void main(String args[]) throws Exception {

        Timer time = new Timer(); // Instantiate Timer Object
        ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
        time.schedule(st, 0, 10000); // Create Repetitively task for every 1 secs

        //for demo only.
        for (int i = 0; i <= 2; i++) {
            MailSender.send("xyz@asd.com", "Welcome to abc", "Welcom eMail");
            Thread.sleep(2000);
            if (i == 2) {
                System.out.println("Application Terminates");
                System.exit(0);
            }
        }
    }
}

ScheduledTask.java

public class ScheduledTask extends TimerTask {

    Date now; // to display current time

    // Add your task here
    public void run() {
        now = new Date(); // initialize date
        System.out.println("Time is :" + now); // Display current time
    }
}

3 个答案:

答案 0 :(得分:0)

您可以使用File类打开目录,并在其上执行listFiles。如果listFiles不返回任何内容,则目录为空。

更好的方法可能是注册文件系统通知,以便每创建一个文件时都会收到通知,而不必每2秒尝试一次。

https://docs.oracle.com/javase/tutorial/essential/io/notification.html

答案 1 :(得分:0)

在MainClass for循环中,您可以按以下方式检查目录状态并发送电子邮件。

File file = new File("Path to your directory for ex. C:\\folder");
if(file.isDirectory()){
    if(file.list().length==0){
        MailSender.send("xyz@asd.com", "Folder is empty", "Folder status");
    }
}

答案 2 :(得分:0)

您可以使用sendMailWhenNoFilesExist实用程序来检查文件夹/文件。通过将文件夹路径作为方法参数传递来从MainClass调用import java.nio.file.Files; import java.nio.file.Paths; . . private void sendMailWhenNoFilesExist(String folderPath) throws IOException { if(Files.isDirectory(Paths.get(folderPath)) && Files.list(Paths.get(folderPath)).count() == 0) { MailSender.send("xyz@asd.com", "Message body", "Message subject"); } } 方法(如下)。

using System.Threading;
using System.Threading.Tasks;
using Application.Persistence;
using MediatR;
using MediatR.Pipeline;
using Microsoft.EntityFrameworkCore;

namespace Application.Application.Users.Commands.CreateUser
{
    public class CreateUserCommandGetMatchingCompanyPreProcess: IRequestPreProcessor<CreateUserCommand>
    {
        private readonly ApplicationDbContext _context;

        public GetMatchingCompanyPreProcessCommand(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task Process(CreateUserCommand request, CancellationToken cancellationToken)
        {
            var domain = new MailAddress(request.EmailAddress).Host;
            var companyId = await _context.Companies.Where(c => c.Domain == domain).Select(c => c.Id).FirstOrDefaultAsync();
            request.CompanyId = companyId;
        }
    }
}