文章来自:http://itnoteshare.com

作者联系方式:a345566462@163.com



使用工具包  javamail 

为什么写这么一篇文章呢。因为使用javamail 通过imap 协议是不可以直接读取 网易邮箱中的邮件的。

Java-Scala 读取163,126邮箱邮件

原因是,网易邮箱并没有按照标准的Imap 协议提供给第三方使用。网易官方说是需要授权码。实际没有那么高大上。就是在Imap 协议的 第二步  一如 ID JSON 。

C2 ID (\"name\" \"com.tencent.foxmail\" \"version\" \"7.2.7.174\" \"os\" \"windows\" \"os-version\" \"6.2\" \"vendor\" \"tencent limited\" \"contact\" \"foxmail@foxmail.com\")
IMAP 协议每一步都是 A 开头,比如第一步  A1  第二步 A2, 网易需要  C开头,如 C1,C2,C3..... 

由于JavaMail 不能直接访问到一些私有属性。这里使用反射实现。

协议包 C开头,默认是 A开头 第二步追加 ID ….

 

C1 CAPABILITY

C2 ID("name" "com.tencent.foxmail" "version""7.2.7.174" "os" "windows" "os-version""6.2" "vendor" "tencent limited""contact" "foxmail@foxmail.com")

C3 LOGIN

C4 CAPABILITY

C5 EXAMINE

原因不详细说了。直接上代码



package com.sun.mail.imap.protocol {

  import java.io.DataOutputStream
  import java.util.Properties
  import javax.mail.{Session, URLName}

  import com.sun.mail.iap.Argument
  import com.sun.mail.imap.IMAPStore
  import com.sun.mail.util.MailLogger

  class Imap2Store(session2: Session, url: URLName) extends IMAPStore(session2: Session, url: URLName) {
    override def newIMAPProtocol(host: String, port: Int) = {
      new IMAP2Protocol(name, host, port, session.getProperties, isSSL, logger)
    }
  }

  class IMAP2Protocol(name: String, host: String, port: Int,
                      props: Properties, isSSL: Boolean, logger: MailLogger)
    extends IMAPProtocol(name: String, host: String, port: Int, props: Properties, isSSL: Boolean, logger: MailLogger) {


    override def writeCommand(command: String, args: Argument): String = {
      val CRLF: Array[Byte] = Array('\r'.toByte, '\n'.toByte)
      // assert Thread.holdsLock(this);
      // can't assert because it's called from constructor
      val output = this.getOutputStream.asInstanceOf[DataOutputStream]

      val tag: String = "C" + Integer.toString({
        val field = this.getClass.getSuperclass.getSuperclass.getDeclaredField("tagCounter")
        field.setAccessible(true)
        var tagCounter = field.getInt(this).asInstanceOf[Integer]
        field.set(this, tagCounter + 1)

        tagCounter += 1
        if (tagCounter == 2) {
          output.writeBytes("C2 ID (\"name\" \"com.tencent.foxmail\" \"version\" \"7.2.7.174\" \"os\" \"windows\" \"os-version\" \"6.2\" \"vendor\" \"tencent limited\" \"contact\" \"foxmail@foxmail.com\")")
          //          println("C2 ID (\"name\" \"com.tencent.foxmail\" \"version\" \"7.2.7.174\" \"os\" \"windows\" \"os-version\" \"6.2\" \"vendor\" \"tencent limited\" \"contact\" \"foxmail@foxmail.com\")")
          tagCounter += 1
          field.set(this, tagCounter)
          output.write(CRLF)
          output.flush()
        }
        field.setAccessible(false)
        tagCounter

      }, 10)

      output.writeBytes(tag + " " + command)
      //      println(tag + " " + command)

      if (args != null) {
        output.write(' ')
        args.write(this)
      }

      output.write(CRLF)
      output.flush()
      tag
    }
  }

}


package com.spider {

  import java.util.Properties
  import java.util.concurrent.{ExecutorService, Executors}
  import javax.mail._

  import com.sun.mail.imap.protocol.Imap2Store

  import scala.io.Source

  /**
    * JaanLuis-TestSpider-2016/10/21
    */
  object TestSpider {

    def loadMail(username: String, password: String): Unit = {

      val protocol = "imap"
      val isSSL = true
      val host = "imap.163.com"
      val port = "143"

      val props = new Properties()
      props.setProperty(s"mail.$protocol.class", classOf[Imap2Store].getName)
      props.setProperty("mail.store.protocol", "imap")
      props.setProperty("mail.imap.host", host)
      props.setProperty("mail.imap.port", port)

      val session = Session.getDefaultInstance(props, new Authenticator() {
        override def getPasswordAuthentication = new PasswordAuthentication(username, password)
      })
      session.addProvider(new Provider(Provider.Type.STORE, "imap", classOf[Imap2Store].getName, "Sun Microsystems, Inc.", "1.4.7"))

      val store = session.getStore(protocol)
      store.connect(username, password)

      val folder = store.getFolder("INBOX")
      folder.open(Folder.READ_ONLY)
      val message = folder.getMessages
//      System.out.println("Messages's length: " + message.length)
      var pmm: ReciveOneMail = null
      var i: Int = 0

      println(username + "\t" + password)

      /*while (i < message.length) {
        pmm = new ReciveOneMail(message(i).asInstanceOf[MimeMessage])

        System.out.println("Message " + i + " subject: " + pmm.getSubject)
        System.out.println("Message " + i + " sentdate: " + pmm.getSentDate)
        System.out.println("Message " + i + " replysign: " + pmm.getReplySign)
        System.out.println("Message " + i + " hasRead: " + pmm.isNew)
        System.out.println("Message " + i + "  containAttachment: " + pmm.isContainAttach(message(i).asInstanceOf[Part]))
        System.out.println("Message " + i + " form: " + pmm.getFrom)
        System.out.println("Message " + i + " to: " + pmm.getMailAddress("to"))
        System.out.println("Message " + i + " cc: " + pmm.getMailAddress("cc"))
        System.out.println("Message " + i + " bcc: " + pmm.getMailAddress("bcc"))
        pmm.setDateFormat("yyMMdd HH:mm")
        System.out.println("Message " + i + " sentdate: " + pmm.getSentDate)
        System.out.println("Message " + i + " Message-ID: " + pmm.getMessageId)
        pmm.getMailContent(message(i).asInstanceOf[Part])
        System.out.println("Message " + i + " bodycontent: \r\n" + pmm.getBodyText)
        //        pmm.setAttachPath("c:\\")
        //        pmm.saveAttachMent(message(i).asInstanceOf[Part])
        i += 1
        i - 1
      }*/

    }

    def main(args: Array[String]): Unit = {

      val pool: ExecutorService = Executors.newFixedThreadPool(100)

      Source.fromFile("D:\\163mailaccount").getLines().foreach {
        line =>
          if (line.split("--").length == 2) {
            pool.submit(new Thread() {
              override def run(): Unit = {
                val Array(username, password) = line.split("--")
                try {
                  loadMail(username, password)
                } catch {
                  case e => /*e.printStackTrace()*/
                }
              }
            })

          }
      }

    }

  }

}
 

文章来自:http://itnoteshare.com

作者联系方式:a345566462@163.com

作者:Drizzly 时间:2016-10-31 浏览 1226评论 0 赞 2砸 0 标签: demo
评论
还可以再输入500个字

请您注意

·自觉遵守:爱国、守法、自律、真实、文明的原则
·尊重网上道德,遵守《全国人大常委会关于维护互联网安全的决定》及中华人民共和国其他各项有关法律法规
·严禁发表危害国家安全,破坏民族团结、国家宗教政策和社会稳定,含侮辱、诽谤、教唆、淫秽等内容的作品
·承担一切因您的行为而直接或间接导致的民事或刑事法律责任
·您在NoteShare上发表的作品,NoteShare有权在网站内保留、转载、引用或者删除
·参与本评论即表明您已经阅读并接受上述条款