Created
January 2, 2019 10:12
-
-
Save tsuemura/e82aec87b085ea6f2f011139ece31059 to your computer and use it in GitHub Desktop.
CodeceptJS: Fetch Email From Mandrill Using Custom Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mandrill = require('mandrill-api/mandrill') | |
const sleep = require('sleep-promise') | |
require('dotenv').config() | |
class FetchMail extends Helper { | |
_before() { | |
this.apiKey = process.env.MANDRILL_API_KEY | |
this.client = new mandrill.Mandrill(this.apiKey) | |
} | |
async grabUrlFromEmail(email) { | |
return email['text'].match(/https?:\/\/[\w/:%#\$&\?\(\)~\.=\+\-]+/)[0] | |
} | |
async fetchMail(mailTo, subject) { | |
const query = `full_email:${mailTo} AND subject:${subject}` | |
const apiKeys = [this.apiKey] | |
const search = (query, apiKeys) => { | |
return new Promise((resolve, reject) => { | |
this.client.messages.search( | |
{ | |
query, | |
apiKeys, | |
limit: 100 | |
}, | |
result => { | |
resolve(result) | |
}, | |
err => { | |
reject(err) | |
} | |
) | |
}) | |
} | |
let searchResult = await search(query, apiKeys) | |
for (var i = 0; i < 12; i++) { | |
if (searchResult['length'] === 0) { | |
await sleep(10000) | |
searchResult = await search(query, apiKeys) | |
} | |
} | |
return new Promise((resolve, reject) => { | |
this.client.messages.content( | |
{ | |
id: searchResult[0]._id | |
}, | |
result => { | |
resolve(result) | |
}, | |
err => { | |
reject(err) | |
}, | |
) | |
}) | |
} | |
} | |
module.exports = FetchMail; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment