关于jar包的下载
jar包包含
mail.jar和activtion.ja
- QQ邮箱配置
1.QQ邮箱-设置 -账户
2.记得保存授权码或者后续重新生成
邮箱更改密码后授权码失效
- 代码部分
/*
主方法测试用
*/
public static void main(String[] args) {
//JavaMail应用-用自己的QQ邮箱来发送服务器的数据
//发送邮件是一件非常耗时的事情,因此这里开辟了另一个线程来专门发送邮件
Sendmail send = new Sendmail();
//启动线程,线程启动之后就会执行run方法来发送邮件
send.start();
}
/用于给用户发送邮件的邮箱
private String from = "xx@qq.com";
//授权码 从QQ上获得
private String password = "olksrttnyqhibegf";
//收件箱
private String to="x@qq.com";
/* 重写run方法的实现,在run方法中发送邮件给指定的用户
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try{
Properties prop = new Properties();
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.host", "smtp.qq.com");
prop.setProperty("mail.smtp.auth", "true");
final String smtpPort = "465";
prop.setProperty("mail.smtp.port", smtpPort);
prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
prop.setProperty("mail.smtp.socketFactory.fallback", "false");
prop.setProperty("mail.smtp.socketFactory.port", smtpPort);
prop.setProperty("mail.debug", "true");
Session session = Session.getDefaultInstance(prop);
session.setDebug(true);
MimeMessage message = createMimeMessage(session, from, to);
Transport transport = session.getTransport();
transport.connect( from, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail) throws Exception {
// 1. 创建一封邮件
MimeMessage message = new MimeMessage(session);
// 2. From: 发件人
message.setFrom(new InternetAddress(sendMail, "测试邮件", "UTF-8"));
// 3. To: 收件人(可以增加多个收件人、抄送、密送)
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "用户名", "UTF-8"));
// 4. Subject: 邮件主题
message.setSubject("测试邮件", "UTF-8");
// 5. Content: 邮件正文(可以使用html标签)
message.setContent("这是一封测试邮件!", "text/html;charset=UTF-8");
// 6. 设置发件时间
message.setSentDate(new Date());
// 7. 保存设置
message.saveChanges();
return message;
}