阿翔编程学-JMail邮件接收类

spring boot 定时任务-接收邮件并且存储附件         在spring boot中写定时任务很简单,两个注解就可以实现。在启动类中加@EnableScheduling ,然后在你需要定时的方法上加上@Scheduled(cron="0 10 8 * * ?");括号内为cron表达式。如下图:              接收邮件及其判断是否有附件,并且存储附件。   public class TimerTaskServi... 阅读详情

package com.jxsafe.source.common.applications.source.classinfo.jmail;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

/**
 * 邮件接收类
 * @author CaoXiang
 *
 */
public class GetMail {

  private int mailCounter; // 邮件计数

  private int mailDownErrorCounter; // 正在下载邮件时,出错的计数器

  private boolean[] recordFailure; // 记录下载出错的邮件的序号

  private int totalRetryTimes; // 总共重试次数,默认为3

  private int retryTimeCounter; // 记下重试的次数

  private Store store;
 
  public Folder folder;

  private Message[] messages;

  private Message message;

  private Part part;

  private int allMessageCount;

  private int messageCount;

  private String dateformat; // 默认的日前显示格式

  private String protocol; // 服务协议

  private String mailHost; // 服务器地址

  private String userName; // 用户名

  private String password; // 密码

  private String emlName; // 下载的邮件名

  private String attachPath; // 邮件及附件下载后的存放目录

  /**
   * 构造一个新的<code>GetMail</code>对象。
   *
   * @throws IOException
   */
  public GetMail() throws IOException {
    totalRetryTimes = 3;
    dateformat = "yyyy-MM-dd hh:ss";
    protocol = "pop3";
    mailHost = "POP.163.com";
    userName = "sxfsongxianfei1";
    password = "1982811";
    attachPath = "c://mail//";
    emlName = "mails";
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setMailHost(java.lang.String)
 */
  public void setMailHost(String mailHost) {
    this.mailHost = mailHost;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMailHost()
 */
  public String getMailHost() {
    return this.mailHost;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setUserName(java.lang.String)
 */
  public void setUserName(String userName) {
    this.userName = userName;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getUserName()
 */
  public String getUserName() {
    return this.userName;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setPassword(java.lang.String)
 */
  public void setPassword(String password) {
    this.password = password;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setStore(javax.mail.Store)
 */
  public void setStore(Store store) {
    this.store = store;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setFolder(javax.mail.Folder)
 */
  public void setFolder(Folder folder) {
    this.folder = folder;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setMessages(javax.mail.Message[])
 */
  public void setMessages(Message[] messages) {
    this.messages = messages;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setMessage(javax.mail.Message)
 */
  public void setMessage(Message message) {
    this.message = message;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessage()
 */
  public Message getMessage() {
    return this.message;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getAllMessageCount()
 */
  public int getAllMessageCount() throws MessagingException {
    this.allMessageCount = folder.getMessageCount();
    return allMessageCount;
  }

  /**
   * 设置allMessageCount
   *
   * @throws MessagingException
   */
  @SuppressWarnings("unused")
  private void setAllMessageCount() throws MessagingException {
    this.allMessageCount = this.folder.getMessageCount();
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessageCount()
 */
  public int getMessageCount() {
    this.messageCount = this.messages.length;
    return messageCount;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getNewMessageCount()
 */
  public int getNewMessageCount() throws MessagingException {
    return this.folder.getNewMessageCount();
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getUnreadMessageCount()
 */
  public int getUnreadMessageCount() throws MessagingException {
    return this.folder.getUnreadMessageCount();
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getPart()
 */
  public Part getPart() {
    return (Part) message;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setPart(javax.mail.Part)
 */
  public void setPart(Part part) {
    this.part = part;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setAttachPath(java.lang.String)
 */

  public void setAttachPath(String attachPath) {
    this.attachPath = attachPath;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getAttachPath()
 */

  public String getAttachPath() {
    return attachPath;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setEmlName(java.lang.String)
 */
  public void setEmlName(String emlName) {
    this.emlName = emlName;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getEmlName()
 */
  public String getEmlName() {
    return emlName;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setDateFormat(java.lang.String)
 */

  public void setDateFormat(String format) throws Exception {
    this.dateformat = format;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getDateFormat(java.lang.String)
 */
  public String getDateFormat(String format) throws Exception {
    return this.dateformat;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getFrom()
 */
  public String getFrom() throws Exception {
    return getFrom(this.message);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getFrom(javax.mail.Message)
 */
  public String getFrom(Message mimeMessage) throws Exception {
    InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
    String from = address[0].getAddress();
    if (from == null)
      from = "";
    String personal = address[0].getPersonal();
    if (personal == null)
      personal = "";
    String fromaddr = personal + "<" + from + ">";
    return fromaddr;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getTOAddress()
 */
  public String getTOAddress() throws Exception {
    return getMailAddress("TO", this.message);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getCCAddress()
 */
  public String getCCAddress() throws Exception {
    return getMailAddress("CC", this.message);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getBCCAddress()
 */
  public String getBCCAddress() throws Exception {
    return getMailAddress("BCC", this.message);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getTOAddress(javax.mail.Message)
 */
  public String getTOAddress(Message mimeMessage) throws Exception {
    return getMailAddress("TO", mimeMessage);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getCCAddress(javax.mail.Message)
 */
  public String getCCAddress(Message mimeMessage) throws Exception {
    return getMailAddress("CC", mimeMessage);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getBCCAddress(javax.mail.Message)
 */
  public String getBCCAddress(Message mimeMessage) throws Exception {
    return getMailAddress("BCC", mimeMessage);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMailAddress(java.lang.String)
 */
  public String getMailAddress(String type) throws Exception {
    return getMailAddress(type, this.message);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMailAddress(java.lang.String, javax.mail.Message)
 */
  public String getMailAddress(String type, Message mimeMessage)
      throws Exception {
    String mailaddr = "";
    String addtype = type.toUpperCase();
    InternetAddress[] address = null;
    if (addtype.equals("TO") || addtype.equals("CC")
        || addtype.equals("BCC")) {
      if (addtype.equals("TO")) {
        address = (InternetAddress[]) mimeMessage
            .getRecipients(Message.RecipientType.TO);
      } else if (addtype.equals("CC")) {
        address = (InternetAddress[]) mimeMessage
            .getRecipients(Message.RecipientType.CC);
      } else {
        address = (InternetAddress[]) mimeMessage
            .getRecipients(Message.RecipientType.BCC);
      }
      if (address != null) {
        for (int i = 0; i < address.length; i++) {
          String email = address[i].getAddress();
          if (email == null)
            email = "";
          else {
            email = MimeUtility.decodeText(email);
          }
          String personal = address[i].getPersonal();
          if (personal == null)
            personal = "";
          else {
            personal = MimeUtility.decodeText(personal);
          }
          String compositeto = personal + "<" + email + ">";
          mailaddr += "," + compositeto;
        }
        mailaddr = mailaddr.substring(1);
      }
    } else {
      throw new Exception("Error emailaddr type!");
    }
    return mailaddr;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getSubject()
 */
  public String getSubject() throws MessagingException {
    return getSubject(this.message);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getSubject(javax.mail.Message)
 */
  public String getSubject(Message mimeMessage) throws MessagingException {
    String subject = "";
    try {
      subject = MimeUtility.decodeText(mimeMessage.getSubject());
      if (subject == null)
        subject = "";
    } catch (Exception exce) {
    }
    return subject;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getSentDate()
 */
  public String getSentDate() throws Exception {
    return getSentDate(this.message);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getSentDate(javax.mail.Message)
 */
  public String getSentDate(Message mimeMessage) throws Exception {
    Date sentdate = mimeMessage.getSentDate();
    SimpleDateFormat format = new SimpleDateFormat(dateformat);
    return format.format(sentdate);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getReplySign()
 */
  public boolean getReplySign() throws MessagingException {
    return getReplySign(this.message);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getReplySign(javax.mail.Message)
 */
  public boolean getReplySign(Message mimeMessage) throws MessagingException {
    boolean replysign = false;
    String needreply[] = mimeMessage
        .getHeader("Disposition-Notification-To");
    if (needreply != null) {
      replysign = true;
    }
    return replysign;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessageId()
 */
  public String getMessageId() throws MessagingException {
    return getMessageId(this.message);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessageId(javax.mail.Message)
 */
  public String getMessageId(Message mimeMessage) throws MessagingException {
    return ((MimeMessage) mimeMessage).getMessageID();
  }

  /**
   * 初始化出错邮件数组
   *
   */
  private void setRecordFailure() {
    this.recordFailure = new boolean[getMessageCount()];
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getRecordFailure()
 */
  public boolean[] getRecordFailure() {
    return this.recordFailure;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#isNew()
 */
  public boolean isNew() throws MessagingException {
    return isNew(this.message);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#isNew(javax.mail.Message)
 */
  public 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;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#isContainAttach()
 */
  public boolean isContainAttach() throws Exception {
    return isContainAttach(this.part);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#isContainAttach(javax.mail.Part)
 */
  public boolean isContainAttach(Part part) throws Exception {
    boolean attachflag = false;
    String contentType = part.getContentType();
    if (part.isMimeType("multipart/*")) {
      Multipart mp = (Multipart) part.getContent();
      for (int i = 0; i < mp.getCount(); i++) {
        BodyPart mpart = mp.getBodyPart(i);
        String disposition = mpart.getDisposition();
        if ((disposition != null)
            && ((disposition.equals(Part.ATTACHMENT)) || (disposition
                .equals(Part.INLINE))))
          attachflag = true;
        else if (mpart.isMimeType("multipart/*")) {
          attachflag = isContainAttach((Part) mpart);
        } else {
          String contype = mpart.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;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getConn()
 */
  public void getConn() {
    try {
      this.getStoreFromServer();
      this.getFolderFromStore();
    } catch (Exception e) {
      mailDownErrorCounter++;
    }
  }

  /**
   * 建立Store连接
   * @return Store
   * @throws Exception
   */
  private Store getStoreFromServer() throws Exception {
    // 创建session
    Session session = Session.getDefaultInstance(System.getProperties(),
        null);
    // session.setDebug(true);

    // 创建store,建立连接
    Store store = session.getStore(protocol);
    System.out.println("connecting");
    store.connect(mailHost, userName, password);
    System.out.println("connected successfully");
    setStore(store);
    return store;
  }

  /**
   * 打开INBox文件夹
   * @return Folder
   */
  private Folder getFolderFromStore() {
    // 打开邮件相应文件夹
    Folder getFolder;
    try {
      getFolder = store.getFolder("INBOX");
      getFolder.open(Folder.READ_WRITE);
      setFolder(getFolder);
      return getFolder;
    } catch (MessagingException e) {
      System.err.println("获取Folder失败!");
      e.printStackTrace();
    }
    return null;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getAllMessages()
 */
  public Message[] getAllMessages() throws MessagingException {
    // 从邮件文件夹获取邮件信息
    Message[] messages = folder.getMessages();
    setMessages(messages);
    setRecordFailure();// 初始化出错数组
    // setMessageCount();
    return messages;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessages(int[])
 */
  public Message[] getMessages(int[] messageNums) throws MessagingException {
    Message[] messages = folder.getMessages(messageNums);
    setMessages(messages);
    setRecordFailure();// 初始化出错数组
    // setMessageCount();
    return messages;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessages(int, int)
 */
  public Message[] getMessages(int start, int end) throws MessagingException {
    Message[] messages = folder.getMessages(start, end);
    setMessages(messages);
    setRecordFailure();// 初始化出错数组
    // setMessageCount();
    return messages;
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMessages(int)
 */
  public Message getMessages(int start) throws MessagingException {
    Message[] messages = folder.getMessages(start, start);
    setMessages(messages);
    setRecordFailure();// 初始化出错数组
    // setMessageCount();
    return messages[0];
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#closeConnection()
 */
  public void closeConnection() {
    try {
      messages = null;
      message = null;
      if (folder.isOpen())
        folder.close(true);
      store.close();
      System.out.println("close");
    } catch (Exception e) {
      System.out.println("关闭和邮件服务器之间连接时出错!");
      e.printStackTrace();
    }
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMail()
 */
  public void getMail() throws Throwable {// 抛出异常,用以重掷
    try {
      parseMessage(message);
    } catch (IOException e) {
      System.err.println("保存邮件出错,检查保存路径");
      throw new IOException("保存邮件出错,检查保存路径");
    } catch (MessagingException e) {
      System.err.println("邮件转换出错");
      throw new MessagingException("邮件转换出错");
    } catch (Exception e) {
      System.err.println("未知错误");
      e.printStackTrace();
      throw new Exception("未知错误");
    }
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getMail(int)
 */
  public void getMail(int index) {
    mailDownErrorCounter = 0; // 邮件下载出错计数器置零
    try {// 获取邮件下载之前的错误
      setMessage(messages[index]);// 设置当前message
      System.out.println("正在获取第" + index+1 + "封邮件. . .");
      getMail();// 获取当前message
      System.out.println("成功获取第" + index+1 + "封邮件");
    } catch (Throwable e) {// 获得重掷异常
      recordFailure[index] = true;
      mailDownErrorCounter++;
      System.err.println("下载第" + index + "封邮件时出错");
      retry();
    }
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#getAllMail()
 */
  public void getAllMail() {
    int mailArrayLength; // 将要下载的邮件的数量。若是重试时,则为还未下载的邮件数量

    mailArrayLength = getMessageCount();

    System.out.println("一共有邮件" + mailArrayLength + "封");

    mailDownErrorCounter = 0; // 邮件下载出错计数器置零
    mailCounter = 0;
    for (int index = 0; index < mailArrayLength; index++) {
      try {
        setMessage(messages[index]);// 设置当前message
        System.out.println("正在获取第" + (index + 1) + "封邮件. . .");
        getMail();// 获取当前message
        System.out.println("成功获取第" + (index+1) + "封邮件");
        mailCounter++;
      } catch (Throwable e) {
        recordFailure[index] = true;
        mailDownErrorCounter++;
        System.err.println("下载第" + index + "封邮件时出错");
      }
    }
    System.out.println("成功下载" + mailCounter + "封邮件");
    mailCounter = 0;
    if (mailDownErrorCounter != 0)
      retry();
  }

  /*
   * 解析邮件
   */
  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#parseMessage(javax.mail.Message)
 */
  public void parseMessage(Message message) throws IOException,
      MessagingException {
    Object content = message.getContent();
    if (content instanceof Multipart) {
      System.out.println("parseMessage....多附档部分");
      handleMultipart((Multipart) content);
    } else {
      System.out.println("parseMessage....单附档部分");
      handlePart(message);
    }
  }

  /*
   * 解析Multipart
   */
  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#handleMultipart(javax.mail.Multipart)
 */
  public void handleMultipart(Multipart multipart) throws MessagingException,
      IOException {
    for (int i = 0, n = multipart.getCount(); i < n; i++) {
      handlePart(multipart.getBodyPart(i));
    }
  }

  /*
   * 解析指定part,从中提取文件
   */
  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#handlePart(javax.mail.Part)
 */
  public void handlePart(Part part) throws MessagingException, IOException {
    System.out.println("解析part开始.......... handlePart");
    String disposition = part.getDisposition(); // Find attachment
    String contentType = part.getContentType();
    InputStreamReader sbis = new InputStreamReader(part.getInputStream());
    if (disposition == null) { // When just body
      System.out.println("part部署disposition 为 Null: " + contentType);
      // Check if plain
      if ((contentType.length() >= 9)
          && (contentType.toLowerCase().substring(0, 9)
              .equals("text/plai"))) {

        System.out.println(getAttachPath() + getEmlName() + ".txt");
        saveFile(getAttachPath() + getEmlName() + ".txt", sbis);
      } else if ((contentType.length() >= 8) // Check if html
          && (contentType.toLowerCase().substring(0, 8)
              .equals("text/htm"))) {
        saveFile(getAttachPath() + getEmlName() + ".html", sbis);
      } else if ((contentType.length() >= 9) // Check if gif
          && (contentType.toLowerCase().substring(0, 9)
              .equals("image/gif"))) {
        saveFile(getAttachPath() + getEmlName() + ".gif", part
            .getInputStream());
      } else if ((contentType.length() >= 9) // Check if jpeg
          && (contentType.toLowerCase().substring(0, 9)
              .equals("image/jpe"))) {
        saveFile(getAttachPath() + getEmlName() + ".jpg", part
            .getInputStream());
      } else if ((contentType.length() >= 10)
          && contentType.toLowerCase().substring(0, 10).equals(
              "multipart/")) { // Check if multipart
        System.out.println("multipart body: " + contentType);
        Multipart mp = (Multipart) (part.getContent());
        handleMultipart(mp);
      } else { // Unknown type
        System.out.println("Other body: " + contentType);
        saveFile(getAttachPath() + getEmlName() + ".txt", sbis);
      }
    } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
      System.out.println(Part.ATTACHMENT + ".. Attachment: "
          + part.getFileName() + " : " + contentType);
      // outToFile.println("Attachment: " + part.getFileName() + " : "
      // + contentType);
      saveFile(getAttachPath() + part.getFileName(), part
          .getInputStream());
    } else if (disposition.equalsIgnoreCase(Part.INLINE)) {
      System.out.println(Part.INLINE + ".. Inline: " + part.getFileName()
          + " : " + contentType);
      // outToFile.println("Inline: " + part.getFileName() + " : "
      // + contentType);
      saveFile(getAttachPath() + part.getFileName(), sbis);
    } else { // Should never happen
      System.out.println("Other: " + disposition);
      // outToFile.println("Other: " + disposition);
      saveFile(getAttachPath() + part.getFileName(), sbis);
    }
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#saveFile(java.lang.String, java.io.Reader)
 */
  public void saveFile(String fileName, Reader input) throws IOException {
    if (fileName == null) {
      fileName = File.createTempFile(getAttachPath() + "xx", ".out")
          .getName();
    }
    // Do no overwrite existing file
    File file = new File(fileName);
    int lastDot = fileName.lastIndexOf(".");
    System.out.println("文件名称为: " + fileName + ">>后缀。位置为: " + lastDot);
    String extension = fileName.substring(lastDot);
    String fullFileName = fileName;
    fileName = fileName.substring(0, lastDot);
    for (int i = 0; file.exists(); 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();
  }

  private void saveFile(String fileName, InputStream in) throws IOException {
    // String temp=part.getFileName();//得到未经处理的附件名字
    // temp= MimeUtility.decodeWord(temp);
    // String s=temp.substring(11,temp.indexOf("?=")-1);//去到header和footer

    // 文件名一般都经过了base64编码,下面是解码
    // String fileName=this.base64Decoder(temp);
    System.out.println("有附件:" + fileName);

    FileOutputStream writer = new FileOutputStream(new File(fileName));
    byte[] content = new byte[255];
    @SuppressWarnings("unused")
    int read = 0;
    while ((read = in.read(content)) != -1) {
      writer.write(content);
    }
    writer.close();
    in.close();
  }

  /*
   * 把指定文件,转化成MimeMessage
   */
  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#readEmlFile(java.lang.String)
 */
  public void readEmlFile(String fileName) throws MessagingException {
    try {
      InputStream fis = new FileInputStream(fileName);
      Session mailSession = Session.getDefaultInstance(System
          .getProperties(), null);
      MimeMessage msg = new MimeMessage(mailSession, fis);
      message = msg;

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }

  @SuppressWarnings("unused")
  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;
  }

  // 当有邮件无法下载时进行重试
  private void retry() {
    mailCounter = 0;
    while (retryTimeCounter < totalRetryTimes && mailDownErrorCounter != 0) {
      if (!store.isConnected() || !folder.isOpen()) {
        System.err.println("与服务器连接断开,请重新连接");
        closeConnection();
        return;
      }

      System.out.println("第" + (retryTimeCounter + 1) + "次重试");

      mailDownErrorCounter = 0; // 邮件下载出错计数器置零

      for (int index = 0; index < getMessageCount(); index++) {
        if (recordFailure[index]) {
          try {
            setMessage(messages[index]);// 设置当前message
            System.out.println("正在获取第" + index+1 + "封邮件. . .");
            getMail();// 获取当前message
            System.out.println("成功获取第" + (index + 1) + "封邮件");
            mailCounter++;
            recordFailure[index] = false;
          } catch (Throwable e) {

            recordFailure[index] = true;
            mailDownErrorCounter++;
            System.err.println("重新下载第" + index + "封邮件时出错");
          }
        }
      }
      retryTimeCounter++;
    }
    System.out.println("成功下载" + mailCounter + "封邮件");
    mailCounter = 0; // 将邮件计数置零
    mailDownErrorCounter = 0;// 下载错误数量归零
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setDelete(javax.mail.Message)
 */
  public void setDelete(Message message) throws MessagingException {
    message.setFlag(Flags.Flag.DELETED, true);

  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#isDelete(javax.mail.Message)
 */
  public boolean isDelete(Message message) throws MessagingException {
    return message.isSet(Flags.Flag.DELETED);
  }

  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#setSeen(javax.mail.Message)
 */
  public void setSeen(Message message) throws MessagingException {
    message.setFlag(Flags.Flag.SEEN, true);

  }

  /*
   * 解析指定part,从中提取文件
   */
  /* (non-Javadoc)
 * @see com.jxsafe.source.common.applications.source.classinfo.jmail.IGetMail#attachPart(javax.mail.Part)
 */
  public void attachPart(Part part) throws MessagingException, IOException {
    System.out.println("解析part开始.......... handlePart");
    String disposition = part.getDisposition(); // Find attachment
    String contentType = part.getContentType();
    if (disposition == null) { // When just body
      System.out.println("part部署disposition 为 Null: " + contentType);
      // Check if plain
      if ((contentType.length() >= 9)
          && (contentType.toLowerCase().substring(0, 9)
              .equals("text/plai"))) {

       
      } else if ((contentType.length() >= 8) // Check if html
          && (contentType.toLowerCase().substring(0, 8)
              .equals("text/htm"))) {
      } else if ((contentType.length() >= 9) // Check if gif
          && (contentType.toLowerCase().substring(0, 9)
              .equals("image/gif"))) {
        saveFile(getAttachPath() + part.getFileName() + ".gif", part
            .getInputStream());
      } else if ((contentType.length() >= 9) // Check if jpeg
          && (contentType.toLowerCase().substring(0, 9)
              .equals("image/jpe"))) {
        saveFile(getAttachPath() + part.getFileName() + ".jpg", part
            .getInputStream());
      } else if ((contentType.length() >= 10)
          && contentType.toLowerCase().substring(0, 10).equals(
              "multipart/")) { // Check if multipart
        System.out.println("multipart body: " + contentType);
        Multipart mp = (Multipart) (part.getContent());
        handleMultipart(mp);
      } else { // Unknown type
        System.out.println("Other body: " + contentType);
      }
    } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
      System.out.println(Part.ATTACHMENT + ".. Attachment: "
          + part.getFileName() + " : " + contentType);
      // outToFile.println("Attachment: " + part.getFileName() + " : "
      // + contentType);
      saveFile(getAttachPath() + part.getFileName(), part
          .getInputStream());
    } else if (disposition.equalsIgnoreCase(Part.INLINE)) {
      System.out.println(Part.INLINE + ".. Inline: " + part.getFileName()
          + " : " + contentType);
      // outToFile.println("Inline: " + part.getFileName() + " : "
      // + contentType);
    } else { // Should never happen
      System.out.println("Other: " + disposition);
      // outToFile.println("Other: " + disposition);
    }
  }
} 

JavaMail接收邮件和附件 (测试可用) package com.xcy; import java.io.*; import java.text.*; import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class PraseMimeMessage{ private MimeMessage mimeMess 阅读详情

相关推荐

Content-Disposition使用方法和注意事项

主要为大家详细介绍了Content-Disposition使用方法和注意事项,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

Javamail操作指南(二)

Bromon原创 请尊重版权 二、 邮件的收取  通常情况下我们都使用pop3协议来收邮件,IMAP嘛现在就不涉及了。收邮件的功能虽然我用了很多时间才基本搞清楚,不过讲起来就so easy了,一个程序就可以基本包括。  邮件大致可以分三种:纯文本邮件、含有其他数据的文本邮件、含有附件的邮件。  CODE   /* * Created on 2004-4-26 */ package org.bro

Sometimes Java 3752

行业龙头牵头组建创新联合体需要提交哪些申报材料?.docx

行业龙头牵头组建创新联合体需要提交哪些申报材料?

JavaMail API

一、JavaMail API简介 JavaMail API是读取、撰写、发送电子信息的可选包。 可用它来建立如Eudora、Foxmail、MS Outlook Express一般的邮件用户代理程序(Mail User Agent,简称MUA,而非邮件传输代理MTA)。 从另外一个角度来看,我们这些电子邮件用户日常用MUA程序来读写邮件,而MUA依赖着MTA处理邮件的递送。 二、相

lvdong3318的专栏 712

jdk17 下载即可安装

jdk17 下载即可安装

SAR成像系列:【3】合成孔径雷达(SAR)的二维回波信号与简单距离多普勒(RD)算法 (附matlab代码)

二维回波信号分析

zr2006_7的专栏 2万+

http上传/下载文件时,Content-Disposition的使用

Content-disposition是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。当 Internet Explorer 接收到头时,它会激活文件下载对话框,它的文件名框自动填充了头中指定的文件名。(请注意,这是设计导致的;无法使用此功能将文档保存到用户的计算机上,而不向用户询问保存位置。) Rfc1867中可查 1.      上传文件请求头: Co

衍夏成歌的博客 7万+

从INCA到Excel:手把手教你移植汽车标定数据的查表插值算法(附源码)

本文详细介绍了如何将汽车标定数据从INCA平台移植到Excel,实现查表插值算法的完整迁移。通过解析INCA MAP数据结构,设计Excel环境下的双线性插值算法,并提供VBA和C#两种实现方案,帮助工程师高效处理标定数据。文章包含实用代码示例和性能优化技巧,适用于ECU开发与标定场景。

weixin_29313239的博客 413

阿翔编程学-JMail邮件发送类

package com.jxsafe.source.common.applications.source.classinfo.jmail;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Addr

曹翔 745

光栅衍射有入射角时_偏振光栅的衍射角度及衍射效率测量

偏振光栅是一种基于入射光的偏振态实现选择性分光的衍射光学元件,衍射角度取决于光栅线数。通过控制入射光的偏振态,偏振光栅能够调控正一阶和负一阶之间的能量分布。当入射光束偏振态不同时,偏振光栅具有不同的衍射特性。理想的偏振光栅:当入射光为右旋圆偏振光时,只有+1级衍射光,衍射光为左旋圆偏振光。当入射光为左旋圆偏振光时,只有-1级衍射光,衍射光为右旋圆偏振光。当入射光为非圆偏振光时,偏振光栅同...

weixin_39552768的博客 6009

永磁同步电机功率计算实战:从公式到避坑指南(附Excel计算模板)

本文详细解析永磁同步电机(PMSM)功率计算的实战技巧,涵盖三维参数体系、三相与单相系统差异、动态工况补偿及常见计算陷阱。特别提供Excel计算模板,帮助工程师快速准确完成功率计算,避免工业应用中的常见错误,提升工作效率。

x8y9z0的博客 812

ie8,contentDisposition

在servlet中,HttpServletResponse有一个表明响应所包含内容类型的参数。对PDF文件而言,内容类型是application/pdf。如果servlet没有设置类型,web浏览器很难决定如何处理这个文件。PDFServlet用下边的代码设置内容类型:resp.setContentType("application/pdf");Content-dispositionContent

冷静地思考 1861

《手把手教你YOLOv9实战》,改进专栏目录

为了提供友好的操作效果,本专栏将会手把手搭建可视化界面,我将用PyQt5 搭建一个可视化界面,可视化界面能够实现基本的图像加载与检测功能,如支持视频、摄像头,还支持更换不同的 YOLOv9 模型,并适应不同领域(如口罩检测系统、人脸检测系统、工业缺陷检测系统等),界面灵活、功能强大。通过YOLOv9加以改进设计,形成新的算法框架,一起水科研和论文,专栏会一直持续更新中,本专栏适合目标检测、分割、分类。

在职AI算法工程师,擅长计算机视觉,YOLO目标检测、分割等,擅长web、pyqt界面可视化,好内容持续更新中,来这里跟大家一起学习,共同进步 2169

javamail解析邮件,内容重复

    最近公司在做一个在自己产品上收发邮件的功能,我有幸参与了这个功能的研发。看了很多javamail的视频,但是大体讲的都十分基础。一些核心的问题,没有涉及。当然这也是要看自己在工作中真正遇到了哪些问题。    在我的负责的项目里,主要是遇到了“用javamail解析邮件内容(邮件内容是纯文本的时候),邮件内容重复”。    出现问题的原因:一些邮件发送出来时,part.getContentT...

qq_26797239的博客 5145

Visual Studio 2022+Qt6.5.3安装教程+环境配置+创建Qt项目+乱码插件+运行很完美(16岁孩子也能看懂)

Visual Studio 2022+Qt6.5.3安装教程+环境配置+创建Qt项目+乱码插件+运行很完美(16岁孩子也能看懂)

Qt历险记,专注Qt技术,三年医疗设备研发经验,1年机器视觉研发经验,半年柔性传感研发经验。 1196

做了一个3DTiles编辑器,支持3DTiles的预览和裁剪导出

3DTiles编辑器的功能极其简洁,核心就是3DTiles格式模型的预览和裁剪。为了演示方便,本文所使用的源数据为mipmap3d[1]网站所提供的无人机拍摄影像,并进行3DTiles构建。打开软件,输入的绝对路径之后,点击添加模型,就可以将模型加载进预览区。之后,点击裁剪模式按钮,默认会出现立方体裁剪框,可通过拖动句柄的方式去调整裁剪框的范围。同时,除了默认的盒体裁切模式外,还支持多边形裁切,点击多边形裁切后,可切换到顶视图,选择重绘多边形,可进行打点绘制。

兴趣使然的创作者 628

通过Java读取QQ邮件及邮件解析

前言 资源下载 基础设置 开启服务 设置收取方式 源码 邮件内容解析前言 最近为了抓取QQ邮箱中部分邮件中的数据,网上找的资料基本都是基于163邮箱的代码,结合部分代码整理出获取QQ邮箱邮件的方式,记录并共享一下。 资源下载mail.jar(用于连接,获取邮件) jsoup.jar(用于解析html)基础设置开启服务 需要开启QQ邮箱的POP3/IMAP服务打开QQ邮箱,并点开设置–>账户

一行Java的博客 2万+

[Dify] 多步对话流程的实现技巧:构建连贯自然的多轮交互系统

摘要:本文探讨了AI系统中实现多轮对话的核心技术与应用方法。文章首先分析了多步对话的典型场景(如机票预订、财务报告生成)及其价值,提出了Dify平台实现该功能的三大机制:变量系统、条件控制和状态管理。随后详细介绍了顺序型、条件型和确认型三种基本对话模式,并通过"会议预约助手"案例展示了实际应用流程。文章还提供了提示词设计、变量引用等实用建议,并强调多轮对话成功的关键在于清晰的结构设计而非单纯依赖模型能力,最终实现自然流畅的人机交互体验。

技术小甜甜:传播可落地技术,帮助个人和企业降低解决真实场景问题的成本 1345

header中Content-Disposition的作用与使用方法

Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。Content-disposition其实可以控制用户请求所得的内容存为一个文件的时候提供一个默认的文件名,文件直接在浏览器上显示或者在访问时弹出文件下载对话框。格式说明: content-disposition = "Content-Disposition" ":" dis...

albert的专栏 3万+

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

javamail接收邮件

import java.io.*;    import java.text.*;    import java.util.*;    import javax.mail.*;    import javax.mail.internet.*;       /**    * 有一封邮件就需要建立一个ReciveMail对象    */   public class ReciveOne

yangshijin1988的专栏 1042

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

获取监控联系人下发来的邮箱附件并下载到服务器本地

private static final Logger log = LoggerFactory.getLogger(ReceiveMail.class); // 账号 @Value("${mail.connect.username}") private String user; // 密码 @Value("${mail.connect.password}") private String password; @Autowired priv

weixin_45501398的博客 748

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

java mail urlname_javamail收发信件时,服务器,收发方的名称应该怎样设置才有效呢

展开全部package com.gwxc.hz.mail.demo;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.text...

weixin_35998457的博客 1526

java mail 收 附件_javamail 收邮件并解析附件

packagecom.zz.mail;import java.io.*;import java.text.*;import java.util.*;import javax.mail.*;import javax.mail.internet.*;importjava.io.File;import jxl.*;/*** 有一封邮件就需要建立一个ReciveMail对象*/public classRe...

weixin_39635459的博客 754
上一篇: 阿翔编程学-JMail邮件发送类
下一篇: 阿翔编程学-Java文件操作
java_xiang
博客等级 码龄20年 14粉丝 42原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址