let mattermostUrl = "https://xxx";
let token = "xxx";
let channelId = "xxx";
let folderId = "xxx";
let folder = DriveApp.getFolderById(folderId);
let pdf2png = "https://xxx.run.app/convert";
function Main() {
let threads = GmailApp.search("is:unread label:inbox subject:Attached Image");
for (let i = 0; i < threads.length; i++) {
let messages = threads[i].getMessages();
for (let j = 0; j < messages.length; j++) {
let message = messages[j];
if (message.isUnread()){
let attachments = message.getAttachments();
if (attachments.length > 0){
let attachment = attachments[0];
if (attachment.getContentType() == "application/pdf") {
CreatePng(attachment);
}
}
message.markRead();
}
}
}
}
function CreatePng(attachment){
let file = folder.createFile(attachment);
file.setName(attachment.getName());
let fileUrl = file.getUrl();
let formData = {
file: file.getBlob()
};
const options = {
method: "post",
payload: formData,
muteHttpExceptions: true
};
let response = UrlFetchApp.fetch(pdf2png, options);
let responseCode = response.getResponseCode();
if (responseCode == 200){
let png = response.getBlob();
PngUploadToMattermost(png,fileUrl)
}
}
function PngUploadToMattermost(attachment,fileUrl) {
let formData = {
files: attachment
}
let endpoint = `${mattermostUrl}/api/v4/files?channel_id=${channelId}`;
let options = {
method: "post",
headers: {
Authorization: `Bearer ${token}`,
},
payload: formData,
muteHttpExceptions: true,
};
let res = UrlFetchApp.fetch(endpoint, options);
PostToMattermost(res,fileUrl);
}
function PostToMattermost(res,fileUrl){
let info = JSON.parse(res.getContentText());
let fileId = info.file_infos[0].id;
let endpoint = `${mattermostUrl}/api/v4/posts`;
let payload = {
channel_id: channelId,
message: `[](${fileUrl})`
}
let options = {
method: "post",
headers: {
Authorization: `Bearer ${token}`,
},
payload: JSON.stringify(payload),
muteHttpExceptions: true,
};
UrlFetchApp.fetch(endpoint, options);
}