- /**
- * 邮件发送
- * @param message 邮件内容
- * @param to 收件人邮箱
- * @param attachment 附件
- */
- public static void sendEmail(String message, String to, File attachment) throws Exception {
- //设置邮件会话参数
- Properties props = new Properties();
- //邮箱的发送服务器地址
- props.setProperty("mail.smtp.host", MAIL_HOST);
- props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
- props.setProperty("mail.smtp.socketFactory.fallback", "false");
- props.put("mail.smtp.ssl.enable", "true");
- //邮箱发送服务器端口,这里设置为465端口
- props.setProperty("mail.smtp.port", "465");
- props.setProperty("mail.smtp.socketFactory.port", "465");
- props.put("mail.smtp.auth", "true");
- //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
- Session session = Session.getDefaultInstance(props, new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(MAIL_USER_NAME, MAIL_AUTH_CODE);
- }
- });
- // 开启调试,生产不开启
- session.setDebug(true);
- Multipart multipart = new MimeMultipart();
- BodyPart contentPart = new MimeBodyPart();
- //contentPart.setContent(message, "text/html;charset=UTF-8");
- contentPart.setText(message);
- multipart.addBodyPart(contentPart);
- if (attachment != null) {
- BodyPart attachmentBodyPart = new MimeBodyPart();
- DataSource source = new FileDataSource(attachment);
- attachmentBodyPart.setDataHandler(new DataHandler(source));
- //MimeUtility.encodeWord可以避免附件文件名乱码
- attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
- multipart.addBodyPart(attachmentBodyPart);
- }
- //通过会话,得到一个邮件,用于发送
- Message msg = new MimeMessage(session);
- //设置发件人
- msg.setFrom(new InternetAddress(MAIL_USER_NAME));
- //设置收件人,to为收件人,cc为抄送,bcc为密送
- msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
- // msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));
- // msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));
- msg.setSubject("我是主题");
- //设置邮件消息
- msg.setContent(multipart);
- //设置发送的日期
- msg.setSentDate(new Date());
- //调用Transport的send方法去发送邮件
- Transport.send(msg);
- }