Ruby从指定邮箱读取邮件(IMAP/POP3)

时间:2022-12-06 19:03:24
  • Documents:
  • 目标:
    • 从收件箱中提取邮件信息
  • Code
     1 require 'net/imap'
    2 require 'net/pop'
    3 require 'mail'
    4 require 'nokogiri'
    5
    6 server='imap.xxx.com'
    7 user='user@xxx.com'
    8 password='password'
    9
    10 imap = Net::IMAP.new(server,{:port=>993,:ssl=>true}) # 需要根据邮件服务器的具体信息进行设置
    11 # imap = Net::IMAP.new(server,{:port=>143,:ssl=>false})
    12 imap.login(user,password)
    13
    14 imap.select("inbox")
    15 imap.search(["NEW"]).each do |id| # 获取符合条件的邮件id集合
    16 # 邮件标题
    17 envelope = imap.fetch(msg_id, "ENVELOPE")[0].attr["ENVELOPE"]
    18 from = Mail::Encodings.value_decode(envelope.from[0].name) # 转换为中文字符
    19 subject = Mail::Encodings.value_decode(envelope.subject)
    20 puts "#{from}: \t#{subject}"
    21
    22 # 邮件正文
    23 body = imap.fetch(msg_id, "BODY[TEXT]")[0].attr["BODY[TEXT]"]
    24 doc = Nokogiri::HTML.parse(body, nil, "UTF-8") # 如果获取的邮件为HTML格式,可以使用nokogiri对其进行处理
    25 ele = doc.xpath("//label//path").inner_text
    26 end
    27
    28 imap.logout
    29 imap.disconnect
    30
    31
    32
    33 server='pop3.xxx.com' # 只要支持imap和pop3都可以使用
    34 user='user@xxx.com'
    35 password='password'
    36
    37 pop = Net::POP3.new server
    38 pop.start user, password
    39
    40 mails = pop.mails.reverse
    41 mail = mails.first # 获取最新一封未读邮件
    42 subject = mail.header.split("\r\n")
    43 body = mail.pop
    44 doc = Nokogiri::HTML.parse(body, nil, "UTF-8")
    45 ele = doc.xpath("//label//path").inner_text
    46
    47 pop.finish