import ballerina.net.http;
import ballerina.util;
import ballerina.config;
import ballerina.log;
string access_token = config:getGlobalValue("gmail_access_token");
public connector GmailConnector () {
action sendMail (string to, string subject, string from, string messageBody, string cc, string bcc, string id,
string threadId) (json responseToSend, http:HttpConnectorError err) {
//creating an endpoint where we indicate the endpoint we are interacting with
endpoint<http:HttpClient> gmailEP {
string baseURL = "https://www.googleapis.com/gmail";
gmailEndpoint = create http:HttpClient(baseURL, {});
}
boolean isExpired;
error e;
error errAccess;
//check if the access token has expired and get a new access token if expired
isExpired, e = isAccessTokenExpired();
if (isExpired) {
access_token, errAccess = getNewAccessToken();
} else if (!isExpired) {
log:printInfo("Access token has not expired");
} else {
log:printError("Error: " + e.msg);
}
//create the message body of the request
http:Request request = {};
http:Response response = {};
string concatRequest = "";
if (to != "null") {
concatRequest = concatRequest + "to:" + to + "\n";
}
if (subject != "null") {
concatRequest = concatRequest + "subject:" + subject + "\n";
}
if (from != "null") {
concatRequest = concatRequest + "from:" + from + "\n";
}
if (cc != "null") {
concatRequest = concatRequest + "cc:" + cc + "\n";
}
if (bcc != "null") {
concatRequest = concatRequest + "bcc:" + bcc + "\n";
}
if (id != "null") {
concatRequest = concatRequest + "id:" + id + "\n";
}
if (threadId != "null") {
concatRequest = concatRequest + "threadId:" + threadId + "\n";
}
if (messageBody != "null") {
concatRequest = concatRequest + "\n" + messageBody + "\n";
}
//encoding the message and create a json message expected by the API
string encodedRequest = util:base64Encode(concatRequest);
json sendMailRequest = {"raw":encodedRequest};
string sendMailPath = "/v1/users/me/messages/send";
request.setHeader("Authorization", "Bearer " + access_token);
request.setHeader("Content-Type", "application/json");
request.setJsonPayload(sendMailRequest);
if (errAccess == null) {
log:printInfo("Access token is " + access_token);
response, err = gmailEP.post(sendMailPath, request);
responseToSend = response.getJsonPayload();
}
return;
}
}
|