基于JavaMail的日历(会议)邮件发送实现
/** * * @param senderAccount 发件人账号 * @param senderPassword 发件人密码 * @param toAddress 收件人邮箱地址 * @param ccAddress 抄送人地址 * @param noticeTitle subject的标题 * @param noticeContent subject的内容 * @param criticalityClass 邮件重要性等级 * @param workShop 车间 * @param line 线体 * @param attachmentPath 附件路径 * @return */ private String sendEmailUtil(String senderAccount, String senderPassword, String toAddress, String ccAddress, String noticeTitle,String noticeContent,String criticalityClass,String workShop,String line,String attachmentPath) { String from=senderAccount+"@sunwoda.com"; String to=toAddress; String location="车间:"+workShop+" 线体:"+line; final String sendAccount=senderAccount; final String sendPwd=senderPassword; // 链接邮件服务器 Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); // 邮件协议 props.put("mail.smtp.host", "smtp.sunwoda.com"); // 服务器域名 props.put("mail.smtp.auth", "true"); //设置用户的认证方式 Authenticator auth = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { String username = sendAccount; // 大多数是你邮件@前面的部分 String pwd = sendPwd; return new PasswordAuthentication(username, pwd); } }; Session mailSession = Session.getInstance(props, auth); // 获取Message对象 Message msg = new MimeMessage(mailSession); try { // 设置邮件基本信息 msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(toAddress)); /*if (toAddress != null && !toAddress.isEmpty()){ InternetAddress[] cc = new InternetAddress().parse(toAddress); msg.setRecipients(Message.RecipientType.TO,cc); }*/ if (ccAddress != null && !ccAddress.isEmpty()){ InternetAddress[] cc = new InternetAddress().parse(ccAddress); msg.setRecipients(Message.RecipientType.CC,cc); } msg.setSentDate(new java.util.Date()); msg.setSubject(noticeTitle); msg.addHeader("ReturnReceipt", "1"); if(criticalityClass.equals("高")){ msg.addHeader("X-Priority", "1"); }else if(criticalityClass.equals("中")){ msg.addHeader("X-Priority", "3"); }else{ msg.addHeader("X-Priority", "5"); } // 获取不同类型的邮件的邮件内容 Multipart mp = getContentText(from,to,location,noticeTitle,noticeContent,criticalityClass,attachmentPath); msg.setContent(mp); msg.saveChanges(); Transport.send(msg); //发送完后删除临时文件 int index=attachmentPath.indexOf('/'); String savePath = StringUtils.getStr(new String[] { this.importFilePath}); String fileName=attachmentPath.substring(index+1); File file = new File(savePath+File.separator+fileName); file.delete(); return "OK"; } catch (Exception ex) { ex.printStackTrace(); String errorInfo= ex.getMessage().substring(0,3); if(errorInfo.equals("535")){ return "发件人邮箱账号或密码错误!"; }else{ return "收件人或抄送人邮箱地址错误!"; } } } private Multipart getContentText(String from,String to,String location1,String noticeTitle,String noticeContent, String criticalityClass,String attachmentPath) throws Exception { String subject =noticeTitle+"-"+noticeContent;//主题里带内容 String content=noticeContent; //取附件路径和名称 int index=attachmentPath.indexOf('/'); String filePath="/"+attachmentPath.substring(0, index); String fileName=attachmentPath.substring(index+1); // 时区 TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry(); TimeZone timezone = registry.getTimeZone("Asia/Shanghai"); // 会议地点 String location = location1; // 会议时间 java.util.Calendar cal = java.util.Calendar.getInstance(); int year=cal.get(java.util.Calendar.YEAR); int month=cal.get(java.util.Calendar.MONTH) + 1; int day=cal.get(java.util.Calendar.DAY_OF_MONTH); int hour=cal.get(java.util.Calendar.HOUR_OF_DAY); int minute=cal.get(java.util.Calendar.MINUTE)+5; cal.setTimeZone(timezone); cal.set(year, month - 1, day, hour, minute); // 月份是要早一个月 DateTime start = new DateTime(cal.getTime()); cal.set(year, month - 1, day, hour+8, minute); DateTime end = new DateTime(cal.getTime()); VEvent vevent = new VEvent(start, end, subject); vevent.getProperties().add(timezone.getVTimeZone().getTimeZoneId());// 时区 vevent.getProperties().add(new Location(location));// 会议地点 vevent.getProperties().add(new Description("公告内容:"+"\n"+content));// 邮件内容 vevent.getProperties().add(new UidGenerator("uidGen").generateUid());// 设置uid //组织者 vevent.getProperties().add(new Organizer(URI.create("mailto:" + from))); // 与会人 Set<String> emailSet = new HashSet<String>(); emailSet.add(from); emailSet.add(to); int i = 1; for (String email : emailSet) { Attendee attendee = new Attendee(URI.create("mailto:" + email)); if (1 == i) { attendee.getParameters().add(Role.REQ_PARTICIPANT); } else { attendee.getParameters().add(Role.OPT_PARTICIPANT); } attendee.getParameters().add(new Cn("Developer" + i)); vevent.getProperties().add(attendee); i++; } // --------VEvent Over---------- // --------VAlarm Start---------- // 提醒,提前5分钟 VAlarm valarm = new VAlarm(new Dur(0, 0, -5, 0)); valarm.getProperties().add(new Repeat(10)); valarm.getProperties().add(new Duration(new Dur(0, 0, 5, 0))); // 提醒窗口显示的文字信息 valarm.getProperties().add(new Summary("Event Alarm")); valarm.getProperties().add(Action.DISPLAY); valarm.getProperties().add(new Description("会议提醒描述,待定,不确定使用方式")); vevent.getAlarms().add(valarm);// 将VAlarm加入VEvent // --------VAlarm Over------------- // --------日历对象 Start--------------- Calendar icsCalendar = new Calendar(); icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN")); icsCalendar.getProperties().add(Version.VERSION_2_0); icsCalendar.getProperties().add(CalScale.GREGORIAN); icsCalendar.getProperties().add(timezone.getVTimeZone().getTimeZoneId()); icsCalendar.getComponents().add(vevent);// 将VEvent加入Calendar // 将日历对象转换为二进制流 CalendarOutputter co = new CalendarOutputter(false); ByteArrayOutputStream os = new ByteArrayOutputStream(); co.output(icsCalendar, os); byte[] mailbytes = os.toByteArray(); // 9. 创建附件"节点" MimeBodyPart attachment = new MimeBodyPart(); //从FTP上下载文件到本地 String savePath = StringUtils.getStr(new String[] { this.importFilePath}); downFileFroFTP("192.168.x.xxx", 21, "xxxxxx", "xxxxx", filePath,fileName, savePath); // 读取本地文件 DataHandler dh2 = new DataHandler(new FileDataSource(savePath+File.separator+fileName)); // 将附件数据添加到"节点" attachment.setDataHandler(dh2); // 设置附件的文件名(需要编码) attachment.setFileName(MimeUtility.encodeText(dh2.getName())); // --------日历对象 Over------------------ MimeMultipart mm = new MimeMultipart(); MimeBodyPart iCalAttachment = new MimeBodyPart(); iCalAttachment.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(mailbytes), "text/calendar;method=REQUEST;charset=UTF-8"))); mm.addBodyPart(iCalAttachment); mm.addBodyPart(attachment); // 添加附件 mm.setSubType("related"); return mm; }