邮件发送
smtp 邮件发送协议
pop3 邮件接收协议
首先开启 SMTP 服务,用qq邮箱做示例。然后生成授权码,用于安全登录。
public class EmailUtil {
/*
* form 邮件发送方地址
* to 邮件接收方地址
* username 发送方名称
* password 授权码
* subject 邮件主题
* text 邮件内容
*/
public static int sendQQMain(String from, String to, String username, String password, String subject , String text ) {
boolean isSSL = true; // 是否启用SSL
// smtp服务器地址(qq),如果是其他平台,比如163,host为 "smtp.163.com"
String host = "smtp.qq.com";
int port = 465; // 邮件服务器端口
boolean isAuth = true; //是否需要身份验证
//创建配置信息
Properties props = new Properties();
props.put("mail.smtp.ssl.enable", isSSL);
props.put("mail.smtp.host", host);
props.put(" mail.smtp.port", port);
props.put("mail.smtp.auth", isAuth);
//验证名称和密码,获取session会话
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(subject);
message.setText(text);
Transport.send(message);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
System.out.println("发送完毕! ");
return 0;
}
}