⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mailreceiver.java

📁 本代码以J2SE 5.0为开发环境
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
				subject = "";
			}
		} catch (Exception exce) {
		}
		return subject;
	}

	/**
	 * 获得邮件发送日期
	 */
	private Date getSentDate() throws Exception {
		return getSentDate(this.currentMessage);
	}

	private Date getSentDate(Message mimeMessage) throws Exception {
		return mimeMessage.getSentDate();
	}

	/**
	 * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
	 */
	private boolean getReplySign() throws MessagingException {
		return getReplySign(this.currentMessage);
	}

	private boolean getReplySign(Message mimeMessage) throws MessagingException {
		boolean replysign = false;
		String needreply[] = mimeMessage
				.getHeader("Disposition-Notification-To");
		if (needreply != null) {
			replysign = true;
		}
		return replysign;
	}

	/**
	 * 获得此邮件的Message-ID
	 */
	private String getMessageId() throws MessagingException {
		return getMessageId(this.currentMessage);
	}

	private String getMessageId(Message mimeMessage) throws MessagingException {
		return ((MimeMessage) mimeMessage).getMessageID();
	}

	/**
	 * 判断此邮件是否已读,如果未读返回返回false,反之返回true
	 */
	private boolean isNew() throws MessagingException {
		return isNew(this.currentMessage);
	}
	private boolean isNew(Message mimeMessage) throws MessagingException {
		boolean isnew = false;
		Flags flags = mimeMessage.getFlags();
		Flags.Flag[] flag = flags.getSystemFlags();
		for (int i = 0; i < flag.length; i++) {
			if (flag[i] == Flags.Flag.SEEN) {
				isnew = true;
				break;
			}
		}
		return isnew;
	}

	/**
	 * 判断此邮件是否包含附件
	 */
	private boolean isContainAttach() throws Exception {
		return isContainAttach(this.currentMessage);
	}
	private boolean isContainAttach(Part part) throws Exception {
		boolean attachflag = false;
		if (part.isMimeType("multipart/*")) {
			// 如果邮件体包含多部分
			Multipart mp = (Multipart) part.getContent();
			// 遍历每部分
			for (int i = 0; i < mp.getCount(); i++) {
				// 获得每部分的主体
				BodyPart bodyPart = mp.getBodyPart(i);
				String disposition = bodyPart.getDisposition();
				if ((disposition != null)
						&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
								.equals(Part.INLINE)))){
					attachflag = true;
				} else if (bodyPart.isMimeType("multipart/*")) {
					attachflag = isContainAttach((Part) bodyPart);
				} else {
					String contype = bodyPart.getContentType();
					if (contype.toLowerCase().indexOf("application") != -1){
						attachflag = true;
					}
					if (contype.toLowerCase().indexOf("name") != -1){
						attachflag = true;
					}
				}
			}
		} else if (part.isMimeType("message/rfc822")) {
			attachflag = isContainAttach((Part) part.getContent());
		}
		return attachflag;
	}

	
	/**
	 * 获得当前邮件
	 */
	private void getMail() throws Exception {
		try {
			this.saveMessageAsFile(currentMessage);
			this.parseMessage(currentMessage);
		} catch (IOException e) {
			throw new IOException("保存邮件出错,检查保存路径");
		} catch (MessagingException e) {
			throw new MessagingException("邮件转换出错");
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("未知错误");
		}
	}
	
	/**
	 * 保存邮件源文件
	 */
	private void saveMessageAsFile(Message message) {
		try {
			// 将邮件的ID中尖括号中的部分做为邮件的文件名
			String oriFileName = getInfoBetweenBrackets(this.getMessageId(message)
					.toString());
			//设置文件后缀名。若是附件则设法取得其文件后缀名作为将要保存文件的后缀名,
			//若是正文部分则用.htm做后缀名
			String emlName = oriFileName;
			String fileNameWidthExtension = this.receiverInfo.getEmailDir()
					+ oriFileName + this.receiverInfo.getEmailFileSuffix();
			File storeFile = new File(fileNameWidthExtension);
			for (int i = 0; storeFile.exists(); i++) {
				emlName = oriFileName + i;
				fileNameWidthExtension = this.receiverInfo.getEmailDir()
						+ emlName + this.receiverInfo.getEmailFileSuffix();
				storeFile = new File(fileNameWidthExtension);
			}
			this.currentEmailFileName = emlName;
			System.out.println("邮件消息的存储路径: " + fileNameWidthExtension);
			// 将邮件消息的内容写入ByteArrayOutputStream流中
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			message.writeTo(baos);
			// 读取邮件消息流中的数据
			StringReader in = new StringReader(baos.toString());
			// 存储到文件
			saveFile(fileNameWidthExtension, in);
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * 解析邮件
	 */
	private void parseMessage(Message message) throws IOException,
			MessagingException {
		Object content = message.getContent();
		// 处理多部分邮件
		if (content instanceof Multipart) {
			handleMultipart((Multipart) content);
		} else {
			handlePart(message);
		}
	}

	/*
	 * 解析Multipart
	 */
	private void handleMultipart(Multipart multipart) throws MessagingException,
			IOException {
		for (int i = 0, n = multipart.getCount(); i < n; i++) {
			handlePart(multipart.getBodyPart(i));
		}
	}
	/*
	 * 解析指定part,从中提取文件
	 */
	private void handlePart(Part part) throws MessagingException, IOException {
		String disposition = part.getDisposition();
		String contentType = part.getContentType();
		String fileNameWidthExtension = "";
		// 获得邮件的内容输入流
		InputStreamReader sbis = new InputStreamReader(part.getInputStream());
		// 没有附件的情况
		if (disposition == null) {
			if ((contentType.length() >= 10)
					&& (contentType.toLowerCase().substring(0, 10)
							.equals("text/plain"))) {
				fileNameWidthExtension = this.receiverInfo.getAttachmentDir()
						+ this.currentEmailFileName + ".txt";
			} else if ((contentType.length() >= 9) // Check if html
					&& (contentType.toLowerCase().substring(0, 9)
							.equals("text/html"))) {
				fileNameWidthExtension = this.receiverInfo.getAttachmentDir()
						+ this.currentEmailFileName + ".html";
			} else if ((contentType.length() >= 9) // Check if html
					&& (contentType.toLowerCase().substring(0, 9)
							.equals("image/gif"))) {
				fileNameWidthExtension = this.receiverInfo.getAttachmentDir()
						+ this.currentEmailFileName + ".gif";
			} else if ((contentType.length() >= 11)
					&& contentType.toLowerCase().substring(0, 11).equals(
							"multipart/*")) {
//				System.out.println("multipart body: " + contentType);
				handleMultipart((Multipart) part.getContent());
			} else { // Unknown type
//				System.out.println("Other body: " + contentType);
				fileNameWidthExtension = this.receiverInfo.getAttachmentDir()
						+ this.currentEmailFileName + ".txt";
			}
			// 存储内容文件
			System.out.println("保存邮件内容到:" + fileNameWidthExtension);
			saveFile(fileNameWidthExtension, sbis);

			return;
		}

		// 各种有附件的情况
		String name = "";
		if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
			name = getFileName(part);
//			System.out.println("Attachment: " + name + " : "
//					+ contentType);
			fileNameWidthExtension = this.receiverInfo.getAttachmentDir() + name;
		} else if (disposition.equalsIgnoreCase(Part.INLINE)) {
			name = getFileName(part);
//			System.out.println("Inline: " + name + " : "
//					+ contentType);
			fileNameWidthExtension = this.receiverInfo.getAttachmentDir() + name;
		} else {
//			System.out.println("Other: " + disposition);
		}
		// 存储各类附件
		if (!fileNameWidthExtension.equals("")) {
			System.out.println("保存邮件附件到:" + fileNameWidthExtension);
			saveFile(fileNameWidthExtension, sbis);
		}
	}
	private String getFileName(Part part) throws MessagingException,
			UnsupportedEncodingException {
		String fileName = part.getFileName();
		fileName = MimeUtility.decodeText(fileName);
		String name = fileName;
		if (fileName != null) {
			int index = fileName.lastIndexOf("/");
			if (index != -1) {
				name = fileName.substring(index + 1);
			}
		}
		return name;
	}
	/**
	 * 保存文件内容
	 * @param fileName	文件名
	 * @param input		输入流
	 * @throws IOException
	 */
	private void saveFile(String fileName, Reader input) throws IOException {

		// 为了放置文件名重名,在重名的文件名后面天上数字
		File file = new File(fileName);
		// 先取得文件名的后缀
		int lastDot = fileName.lastIndexOf(".");
		String extension = fileName.substring(lastDot);
		fileName = fileName.substring(0, lastDot);
		for (int i = 0; file.exists(); i++) {
			// 如果文件重名,则添加i
			file = new File(fileName + i + extension);
		}
		// 从输入流中读取数据,写入文件输出流
		FileWriter fos = new FileWriter(file);
		BufferedWriter bos = new BufferedWriter(fos);
		BufferedReader bis = new BufferedReader(input);
		int aByte;
		while ((aByte = bis.read()) != -1) {
			bos.write(aByte);
		}
		// 关闭流
		bos.flush();
		bos.close();
		bis.close();
	}

	/**
	 * 获得尖括号之间的字符
	 * @param str
	 * @return
	 * @throws Exception
	 */
	private String getInfoBetweenBrackets(String str) throws Exception {
		int i, j; //用于标识字符串中的"<"和">"的位置
		if (str == null) {
			str = "error";
			return str;
		}
		i = str.lastIndexOf("<");
		j = str.lastIndexOf(">");
		if (i != -1 && j != -1){
			str = str.substring(i + 1, j);
		}
		return str;
	}

	public static void main(String[] args) throws Exception {
		MailReceiverInfo receiverInfo = new MailReceiverInfo();
		receiverInfo.setMailServerHost("pop.163.com");
		receiverInfo.setMailServerPort("110");
		receiverInfo.setValidate(true);
		receiverInfo.setUserName("***");
		receiverInfo.setPassword("***");
		receiverInfo.setAttachmentDir("C:/temp/mail/");
		receiverInfo.setEmailDir("C:/temp/mail/");

		MailReceiver receiver = new MailReceiver(receiverInfo);
		receiver.receiveAllMail();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -