用Java来实现邮件发送功能,在此期间自己遇到了一个小问题,困扰了我比较长的时间,后来发现竟然是因为true没有加上引号,当时我也是醉~^_^~
闲话少说,直接上代码
public static void main(String[] args) {
String from = "发送者@163.com";
String to = "接收者@163.com";
final String username = "发送者@163.com";
final String password = "密码";
Properties props = new Properties();
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.port", 465);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("主题");
message.setText("测试邮件");
Transport.send(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
System.out.println("发送完毕!");
}