gpt4 book ai didi

java - 如何每天在特定时间使用java发送邮件

转载 作者:行者123 更新时间:2023-11-28 23:12:19 24 4
gpt4 key购买 nike

我正在开发一个使用 JavaservletJSP 并使用 apache Tomcat 作为应用服务器的 web_application

我做了什么

  • 我创建了一个UI,用户可以在其中选择邮件 ID(他们可以选择多个)
  • 当用户点击发送按钮时,我会触发我的 java 类并发送邮件

现在我要做的

  • 现在我必须动态地执行此操作,每天晚上 12:00 我必须向某些特定用户发送邮件

  • 我必须向其发送邮件的用户我正在从登录查询中获取该邮件 ID,因此这不是问题

  • 我只想知道半夜12:00怎么发邮件

我到现在为止做过的编码

servlet 类

public class EmailSendingServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
private String host;
private String port;
private String user;
private String pass;

public void init() {

ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String recipient = request.getParameter("To"); // this i will get from login query
String subject = request.getParameter("subject");//this i can define manually
String content = request.getParameter("content");//same for this also


String resultMessage = "";

try {
EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
content);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
}
}

Java 实用类

public class EmailUtility {
public static void sendEmail(String host, String port, final String userName, final String password,
String toAddress, String subject, String message) throws AddressException, MessagingException {


Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
session.setDebug(false);
Message msg = new MimeMessage(session);

msg.setFrom(new InternetAddress(userName));
if (toAddress!= null) {
List<String> emails = new ArrayList<>();
if (toAddress.contains(",")) {
emails.addAll(Arrays.asList(toAddress.split(",")));
} else {
emails.add(toAddress);
}
Address[] to = new Address[emails.size()];
int counter = 0;
for(String email : emails) {
to[counter] = new InternetAddress(email.trim());
counter++;
}
msg.setRecipients(Message.RecipientType.TO, to);
}
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);

Transport.send(msg);

}

最佳答案

您可以使用 ScheduledExecutorService 在“普通”Java 中处理此问题:

 ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
int count = 0;

Runnable task = () -> {
count++;
System.out.println(count);
};

ScheduledFuture<?> scheduledFuture = ses.scheduleAtFixedRate(task, 12, TimeUnit.HOURS);

还有一种使用初始延迟的方法,但您可以在此处阅读更多内容: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

对于您的用例:

引入一个新类EmailSendJobUtil:

public class EmailSendUtil {
public void createAndSubmitSheduledJob() {
ScheduledExecutorService ses = Executors.sheduledThreadPool(1);
ScheduledFuture<> sheduledFuture = ses.sheduleAtFixedRate(EmailUtility.sendMail(), 12, TimeUnit.HOURS);
}
}

但是,您会遇到代码结构方面的问题。尝试在您的 EmailUtility 中引入一种封装自动发送邮件的方法。

引入一个存储库来保存您必须自动向哪些用户发送邮件,并以仅处理自动发送的新方法读取此数据。你可以这样做:

public class MailJobRepository {
private List<MailJob> jobs;

void add();
void remove();
List<> getJobs();
}

并在您的 EmailUtility 中引入一个新方法:

public void sendAutomatedEmails() {
jobRepository.getJobs().foreach(job -> {
sendMail(job.getToAddress(), job.getSubject(), job.getMessage());
});
}

然后您可以调度这个新方法,并且您已将代码拆分为逻辑上独立的部分。

一点提示:

String host, String port, final String userName, final String password  

这是您发送电子邮件的“一方”的数据,不应作为方法参数传递。您可以将此数据保存到您的 EmailUtility 类中。

关于java - 如何每天在特定时间使用java发送邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56124262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com