基於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; }