1、拼装表格
//拼装表格startStringBuilder content = new StringBuilder("<html><head></head><body><h2>【运管平收台预警提醒】:"+DateUtil.format(new Date(),"yyyy年MM月dd日")+"当前已交收资金!</h2>");content.append("<h>"+DateUtil.format(new Date(),"yyyy年MM月dd日")+"当前已交收资金详情:</h>");content.append("<table border=\"5\" style=\"border:solid 1px #E8F2F9;font-size=14px;;font-size:18px;\">");content.append("<tr style=\"background-color: #428BCA; color:#ffffff\"><th>资产单元</th><th>收款汇总总额</th></tr>");for (int i = 0;i < size; i++) {content.append("<tr>");content.append("<td>" + receiptVos.get(i).getAssetId() + "</td>"); //第一列content.append("<td>" + receiptVos.get(i).getTotalMoney()+ "</td>"); //第二列content.append("</tr>");}content.append("</table>");content.append("</body></html>");//拼装表格end
2、发送邮件
public void sendMail(JavaMailVO mailVO){Session session = Session.getInstance(PROP);Message msg = new MimeMessage(session);Multipart multipart = new MimeMultipart();BodyPart contentPart = new MimeBodyPart();try (Transport transport = session.getTransport()){msg.setSubject(mailVO.getSubject());msg.setFrom(new InternetAddress(mailFrom));//保存正文contentPart.setContent(mailVO.getContent(), "text/html;charset=UTF-8");multipart.addBodyPart(contentPart);//如果有附件上传附件if (CollectionUtil.isNotEmpty(mailVO.getAttachments())) {for (File attachment : mailVO.getAttachments()) {BodyPart attachmentBodyPart = new MimeBodyPart();DataSource source = new FileDataSource(attachment);attachmentBodyPart.setDataHandler(new DataHandler(source));attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));multipart.addBodyPart(attachmentBodyPart);}}//设置收件人InternetAddress[] addresses = new InternetAddress[mailVO.getTo().length];for (int i = 0; i < mailVO.getTo().length; i++) {addresses[i] = new InternetAddress(mailVO.getTo()[i]);}msg.addRecipients(Message.RecipientType.TO,addresses);msg.setContent(multipart);msg.saveChanges();transport.connect(userName,password);//发件人邮箱,授权码(可以在邮箱设置中获取到授权码的信息)transport.sendMessage(msg, msg.getAllRecipients());} catch (Exception e) {log.error("本次发送邮件失败,时间:{},错误原因:{}", DateUtil.formatDate(new Date(),"yyyy-MM-dd HH:mm:ss"),e);}}
然后就成功啦,在配置文件设置发件人的邮箱和授权码