发邮件功能
先导javac.mail.jar包
public static String sendEmail(String smtpAuth, String smtpHost, String smtPort, String fromMail, String password,
String toMail, String mailTitle, String mailContent, String type) {
// 创建Properties 类用于记录邮箱的一些属性
Properties properties = new Properties();
// 表示SMTP发送邮件,必须进行身份验证
properties.put("mail.smtp.auth", smtpAuth);
// 此处填写SMTP服务器
properties.put("mail.smtp.host", smtpHost);
// 端口号,QQ邮箱给出了两个端口,这里用587
properties.put("mail.smtp.port", smtPort);
// 此处填写你的账号
properties.put("mail.user", fromMail);
// 此处的密码是16位STMP口令
properties.put("mail.password", password);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromMail, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(properties, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
// 设置发件人
InternetAddress form = null;
// 设置收件人的邮箱
InternetAddress to = null;
try {
form = new InternetAddress(fromMail);
message.setFrom(form);
to = new InternetAddress(toMail);
message.setRecipient(RecipientType.TO, to);
// 设置邮件标题
message.setSubject(mailTitle);
// 设置邮件的内容体
message.setContent(mailContent, "text/html;charset=UTF-8");
// 最后当然就是发送邮件啦
Transport.send(message);
} catch (AddressException addressException) {
addressException.printStackTrace();
} catch (MessagingException messagingException) {
messagingException.printStackTrace();
}
return "success";
}

浙公网安备 33010602011771号