package utils; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; /** * Requires mail.jar */ public class MailSender { private String username; private String password; private String sendto; private String subject; private String htmlbody; public MailSender(String username, String password, String sendto, String subject, String htmlbody) { super(); this.username = username; this.password = password; this.sendto = sendto; this.subject = subject; this.htmlbody = htmlbody; } public String qqsending() throws MessagingException { // 基本设置 Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.qq.com"); props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); Message msg = new MimeMessage(session); // 邮件正文(html) Multipart mp = new MimeMultipart(); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlbody, "text/html; charset=utf-8"); mp.addBodyPart(htmlPart); // 其它设置 msg.setFrom(new InternetAddress(username + "@qq.com")); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sendto, false)); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setContent(mp); // 发送 Transport.send(msg); return "success"; } }