如何使用不使用浏览器的量角器登录gmail帐户并阅读邮件

时间:2018-06-24 02:15:32

标签: javascript email protractor

我有一种情况,我需要登录到Gmail帐户并阅读内容或消息。然后需要从该消息中获取URL。我可以使用量角器中的浏览器执行此操作。但是问题是gmail帐户启用了2FA。我已经使用核心Selenium实现了这一点,该核心具有使用IMAP协议登录到gmail帐户的jar文件。

有人可以给我一个好的解决方案吗?

2 个答案:

答案 0 :(得分:1)

您可以使用mail-listener2 npm软件包在量角器测试中阅读来自Gmail的电子邮件。检查以下示例代码。

mailListener.ts

const MailListenerClient = require("mail-listener2");
const cheerio = require('cheerio');
const simpleParser = require('mailparser').simpleParser;
export class MailListener {

  public mailListener:any;

  constructor() {
      this.mailListener = new MailListenerClient({
          username: "username@gmail.com",
          password: "password",
          host: "imap.gmail.com",
          port: 993,
          tls: true,
          mailbox: "INBOX",
          searchFilter: ["UNSEEN", ["FROM", "fromemail@gmail.com"],["SUBJECT","subject of the email"]], 
          /*it will search for are "unseen" mail send from "fromemail@gmail.com" with subject "fromemail@gmail.com"*/
          connTimeout: 10000,
          authTimeout: 5000,
          markSeen: true,
          mailParserOptions: {streamAttachments: true}, // options to be passed to mailParser lib.
          attachments: true, // download attachments as they are encountered to the project directory
          attachmentOptions: {directory: "attachments/"},
          debug : console.log
       });
   }

  init() {
      this.mailListener.start();
  }

  close() {
     this.mailListener.stop();
  }


  getLinkFromEmail() {
      var self = this;
      return new Promise((resolve, reject) => {
          self.mailListener.on("mail", function (mail) {
              /*simpleParser is used to convert string to HTML format*/
              simpleParser(mail.eml).then(function (parsedEmail) {
                  var html = parsedEmail.html;
                  /* cheerio is used to write query on parsed HTML content
                   * refer https://www.npmjs.com/package/cheerio 
                   */
                  resolve(cheerio.load(html)("a").attr("href"));
              });
          });

          self.mailListener.on("error", function (err) {
             reject(err);
          });
      });
  }

}

test.ts

import {MailListener} from "mailListner";

describe("Read email from gmail using imap", function () {
  let mailListener = new MailListener();

  beforeAll(function(){
    mailListener.init();
  });

  afterAll(function(){
    mailListener.close();
  })

  it("Test email recieved",function(){
       let urlFromEmail =  mailListener.getLinkFromEmail();

       /*Perform some action on UI that triggers email.(Just for example im doing it)*/
       element(by.id("email")).sendKeys("email@gmail.com");
       element(by.buttonText("Send Email")).click();
       expect(urlFromEmail).toEqual("some link");
    })
});

我已经用打字稿编写了代码,希望您可以用javascript重写同样的代码。让我知道是否很清楚,还是需要在代码中添加更多详细信息。

答案 1 :(得分:0)

最佳实践之一是使用Gmail API。看看official documentation