Search code examples
httpgmailballerina

Ballerina : How to send attachment with email


I am using wso2/gmail package to send an email notification. According to the documentation (https://central.ballerina.io/wso2/gmail) we can send an attachment with the mail through the package. However, when I try to define attachment paths as a parameter, I get an error as follows.

incompatible types: expected 'wso2/gmail:0.9.7:AttachmentPath', found 'string'

What is AttachmentPath type? Can we parse string array of attachment paths to AttachmentPath? Here is my function to send mail.

import wso2/gmail;
import ballerina/io;
import ballerina/log;
import ballerina/config;
import ballerina/http;

function sendErrorLogMail(string senderEmail, string recipientEmail, string subject, string messageBody) returns boolean {
    endpoint gmail:Client gmailErrorClient {
        clientConfig:{
            auth:{
                accessToken:config:getAsString("gmailApiConfiguration.accessToken"),
                refreshToken:config:getAsString("gmailApiConfiguration.refreshToken"),
                clientId:config:getAsString("gmailApiConfiguration.clientId"),
                clientSecret:config:getAsString("gmailApiConfiguration.clientSecret")
            }
        }
    };

    gmail:MessageRequest messageRequest;
    messageRequest.recipient = recipientEmail;
    messageRequest.sender = senderEmail;
    messageRequest.subject = subject;
    messageRequest.messageBody = messageBody;
    messageRequest.contentType = gmail:TEXT_HTML;

    //What is the attachment path?
    AttachmentPath attachmentPath = "./org/wso2/logs/loginfo.txt";

    messageRequest.attachmentPaths = attachmentPath;

    var sendMessageResponse = gmailErrorClient->sendMessage(senderEmail, untaint messageRequest);
    string messageId;
    string threadId;
    match sendMessageResponse {
        (string, string) sendStatus => {
            (messageId, threadId) = sendStatus;
            log:printInfo("Sent email to " + recipientEmail + " with message Id: " + messageId + " and thread Id:"
                    + threadId);
            return true;
        }
        gmail:GmailError e => {
            log:printInfo(e.message);
            return false;
        }
    }
}

Solution

  • AttachmentPath is defined in [wso2/gmail][1] as a record. The attachmentPaths field needs an array of such AttachmentPath objects. So following should work.

    gmail:AttachmentPath attachmentPath= {
            attachmentPath:"./org/wso2/logs/loginfo.txt",
            mimeType:"text/plain"
    };
    
    messageRequest.attachmentPaths = [attachmentPaths];