mailgun/ts/mailgun.classes.account.ts
2020-01-11 19:01:59 +00:00

99 lines
2.7 KiB
TypeScript

import * as plugins from './mailgun.plugins';
export class MailgunAccount {
public baseUrl = 'https://api.mailgun.net/v3';
public baseUrlSe = 'https://se.api.mailgun.net/v3';
public apiToken: string;
constructor(apiTokenArg: string) {
this.apiToken = apiTokenArg;
}
public getRequest(routeArg: string) {
let requestUrl = routeArg;
const needsBaseUrlPrefix = (routeArg.startsWith(this.baseUrl)) || routeArg.startsWith(this.baseUrlSe);
needsBaseUrlPrefix ? requestUrl = `${this.baseUrl}${routeArg}` : null;
const response = plugins.smartrequest.request(requestUrl, {
method: 'GET',
headers: {
Authorization: `Basic ${plugins.smartstring.base64.encode(
`api:${this.apiToken}`
)}`,
'Content-Type': 'application/json'
}
});
return response;
}
public async postFormData(routeArg: string, formFields: plugins.smartrequest.IFormField[]) {
const requestUrl = `${this.baseUrl}${routeArg}`; // TODO;
const response = await plugins.smartrequest.postFormData(
requestUrl,
{
headers: {
Authorization: `Basic ${plugins.smartstring.base64.encode(
`api:${this.apiToken}`
)}`
}
},
formFields
);
return response;
}
/**
* sends a SmartMail
*/
public async sendSmartMail(smartmailArg: plugins.smartmail.Smartmail, toArg: string, dataArg = {}) {
const domain = smartmailArg.options.from.split('@')[1];
const formFields: plugins.smartrequest.IFormField[] = [
{
name: 'from',
type: 'string',
payload: smartmailArg.options.from
},
{
name: 'to',
type: 'string',
payload: toArg
},
{
name: 'subject',
type: 'string',
payload: smartmailArg.getSubject(dataArg)
},
{
name: 'html',
type: 'string',
payload: smartmailArg.getBody(dataArg)
}
];
for (const attachment of smartmailArg.attachments) {
formFields.push({
name: 'attachment',
type: 'Buffer',
payload: attachment.contentBuffer,
fileName: attachment.parsedPath.base
});
}
const response = await this.postFormData(`/${domain}/messages`, formFields);
if (response.statusCode === 200) {
return response.body;
} else {
console.log(response.body);
throw new Error('could not send email');
}
}
public async retrieveSmartMailFromMessageUrl(messageUrlArg: string) {
const response = await this.getRequest(messageUrlArg);
return response.body;
}
public async retrieveSmartMailFromNotifyPayload(notifyPayloadArg: any) {
return await this.retrieveSmartMailFromMessageUrl(notifyPayloadArg['message-url']);
}
}