这里我们使用qq邮箱为例来进行定时自动发送邮件的编写
首先我们需要打开发送方qq邮箱的pop3/SMTP服务
然后会收到一个16位的SMTP口令,记住很有用
首先我们会用到两个jar包来完成:
1.mail.jar编辑自动发送mail
2.actvation.jar添加邮件的附件进行仪器发送
一.配置所需要的相关的信息(一般使用properties来进行配置信息的存放):
//创建Properties类用于记录邮箱的一些属性
final Properties props = new Properties();
//表示使用SMTP发送邮件,必须进行身份验证
props.put("mail.smtp.auth", "true");
//此处填写SMTP服务器
props.put("mail.smtp.host", "smtp.qq.com");
//端口号587或465
props.put("mail.smtp.port", "587");
//此处填写你的账号
props.put("mail.user", "19......045@qq.com");
//此处填写前面说到的16 位SMTP口令
props.put("mail.password", "口令");
3.身份验证
//构建授权信息用于SMTP进行身份验证,密码,账号验证
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
//用户名,密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
4.使用配置信息和,授权信息创建邮件会话
//使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
5.创建邮件消息,及发件人,收件人
//创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
//设置发件人
InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
message.setFrom(form);
//设置收件人的邮箱
InternetAddress to = new InternetAddress("15。。。。@163.com");
message.setRecipient(RecipientType.TO, to);
6.内容
//设置邮件标题
message.setSubject("您好,我的第一份邮件");
//设置邮件的内容
message.setContent("加油,兄弟","text/html;charset=UTF-8");
7.添加邮件的附件actvation
Multipart mp = new MimeMultipart();
BodyPart part = new MimeBodyPart();
// 获取附件地址
Properties filePro = new Properties();
//引入地址信息
filePro.load(this.getClass().getClassLoader().getResourceAsStream("propertiesFile/config.properties"));
//附件的地址
DataSource source = new FileDataSource(filePro.getProperty("filePath"));
//DataSource source = new FileDataSource("D:\\123.png");
System.out.println();
part.setDataHandler(new DataHandler(source));
//设置附件的名
part.setFileName("123.png");
//添加附件到附件载体中
mp.addBodyPart(part);
//将附件加入邮件信息
message.setContent(mp);
8.发送邮件
Transport.send(message);
System.out.println("发送完成》》》》》》》》》》》》》》》》》》");
9.至于定时发送,则是在该工具类的基础上,使用timer或者aquartz来实现定时调用即可
final static int Day_Month = 19;//每月19号
final static int Hour_Date = 8;//八点
final static int Minute_Hour = 8;//8分
final static int Second_Minute = 8;
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH,Day_Month);
c.set(Calendar.HOUR_OF_DAY, Hour_Date);
c.set(Calendar.MINUTE, Minute_Hour);
c.set(Calendar.SECOND, Second_Minute);
final Date time = c.getTime();
final AutoSendMailUtil autoSendMailUtil = new AutoSendMailUtil();
System.out.println("开始执行任务");
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
autoSendMailUtil.sendEmail();
System.out.println("发送成功");
} catch (MessagingException | IOException e) {
// TODO Auto-generated catch block
System.out.println("发送邮件失败,呼叫彬哥!");
e.printStackTrace();
}
}
}, time, 1000*60*60*24);