进邮箱,账号,开启SMTP服务,得到授权码,下载javax.mail.jar引入 public static void main(String[] args) throws Exception {
testEmail3();
}private static void testEmail3() {
try {
Properties properties = new Properties();
properties.put("mail.transport.protocol", "smtp");// 连接协议
properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
properties.put("mail.smtp.port", 465);// 端口号
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.enable", "true");//设置是否使用ssl安全连接 ---一般都使用
properties.put("mail.debug", "true");//设置是否显示debug信息 true 会在控制台显示相关信息
//得到回话对象
Session session = Session.getInstance(properties);
// 获取邮件对象
Message message = new MimeMessage(session);
//设置发件人邮箱地址
message.setFrom(new InternetAddress("838139000@qq.com"));
//设置收件人地址
// message.setRecipients( RecipientType.TO,InternetAddress.parse("838139341@qq.com"));
// Cc: 抄送(可选)
// message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("838139000@qq.com", "那麽", "UTF-8"));
// Bcc: 密送(可选)
message.setRecipients(RecipientType.BCC, InternetAddress.parse("1499414000@qq.com"));
//设置邮件标题
message.setSubject("主题");
//设置邮件内容
message.setText("内容为: 这是第一封java1发送来的邮件。");
// 6. 设置显示的发件时间
message.setSentDate(new Date());
// 7. 保存前面的设置
message.saveChanges();
//得到邮差对象
Transport transport = session.getTransport("smtp");
//连接自己的邮箱账户
transport.connect("838139000@qq.com", "密码");//发送账户和密码为刚才得到的授权码
//发送邮件
transport.sendMessage(message, message.getAllRecipients());
// 8. 将该邮件保存到本地
OutputStream out = new FileOutputStream("D:/MyEmail.eml");
message.writeTo(out);
out.flush();
out.close();
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}