我正在使用nu7'hatch/gmail gem进入我的Gmail帐户并收到电子邮件。我可以正确抓取Date
和Subject
,但对于From
和Body
我也会获得这些字符,而我无法简单地获取文字:
自:
--- - !ruby/struct:Net::IMAP::Address name: [NAME_OF_SENDER_IS_HERE] route: mailbox: [USERNAME_OF_SENDER_IS_HERE] host: gmail.com
身体:
--- !ruby/object:Mail::Body boundary: preamble: epilogue: charset: US-ASCII part_sort_order: - text/plain - text/enriched - text/html parts: !ruby/array:Mail::PartsList [] raw_source: [MESSAGE_GOES_HERE] encoding: 7bit
有没有办法正确获取From和Body文本,没有这些字符?
答案 0 :(得分:3)
我找到的解决方法是使用Net :: IMAP。
请注意,From
所需的电子邮件已完成mail.from[0]
。
imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)
imap.login(USERNAME, PASSWORD)
imap.select('Inbox')
imap.search(["ALL"]).each do |message_id|
emails = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
mail = Mail.read_from_string emails
@email = Email.create(:subject => mail.subject, :message => mail.body.decoded, :sender => mail.from[0], :date => mail.date)
end
imap.disconnect
答案 1 :(得分:0)
您可以执行类似
的操作这一行返回完整的结构:
gmail.inbox.find(subject: "yoursubject").first.envelope
...在结构上你可以:
gmail.inbox.find(subject: "yoursubject").first.envelope.reply_to[0].mailbox
gmail.inbox.find(subject: "yoursubject").first.envelope.reply_to[0].name
gmail.inbox.find(subject: "yoursubject").first.envelope.reply_to[0].host
...然后将您的操作组合成一个字符串,该字符串将被评估为:
name <sample@sample.com>