代码很简单,两个方法:随机方法、发送邮件方法。如果需要更改随机方法,直接将方法重写即可。
代码:
package com.eat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class LunchDecider {
private static final String[] options = {
"面", "小厨", "乡村基", "米线", "粉", "小碗菜"};
private static final String recipient1 = "[email protected]";
// 多个邮箱配置到这里
private static final String recipient2 = "[email protected]";
private static final String recipient3 = "[email protected]";
// 发送邮箱的配置
private static final String sender = "[email protected]";
// smtp密钥,不是邮箱密码,不懂自己百度
private static final String password = "klbkixshfssbcaia";
private static final String host = "smtp.qq.com";
public static void main(String[] args) {
// 获取吃什么
String selectedOption = getRandomOption();
// 发送邮箱
sendEmail(selectedOption, recipient1, recipient2, recipient3);
}
private static String getRandomOption() {
List<String> optionList = new ArrayList<>();
Collections.addAll(optionList, options);
Collections.shuffle(optionList);
return optionList.get(0);
}
private static void sendEmail(String selectedOption, String... recipients) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "465");
Session session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sender, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
InternetAddress[] addresses = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addresses[i] = new InternetAddress(recipients[i]);
}
message.setRecipients(Message.RecipientType.TO, addresses);
message.setSubject("午餐吃什么抽取结果");
message.setText("今天我们吃:" + selectedOption + "。冲冲冲!");
Transport.send(message);
System.out.println("邮件发送成功!");
} catch (Exception e) {
System.out.println("邮件发送失败!");
e.printStackTrace();
}
}
}
pom依赖:
<dependencies>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
</dependencies>