Sending Emails from SAP CAP Applications with Any SMTP Provider

Estimated read time 10 min read

 

Sending Emails from SAP CAP Applications with Any SMTP Provider

Step 1: Prepare Your Mail Account

Enable 2-Step Verification if your provider requires it (Gmail does).Generate an App Password or special SMTP password. This is safer than using your regular password.

        Navigate to Google Account->Security

     

 

      Search application password

      

 

 

Step 2 : Create a Destination in SAP BTP Cockpit

A destination in BTP stores connection details to external systems (in this case, Gmail SMTP).
Here’s what you do:

Go to your SAP BTP Cockpit → Destinations.Create a new destination with:Name: GmailSMTPType: SMTPAuthentication: BasicAuthenticationUser: Password: The 16-character App Password generated from GoogleAdditional properties like host: smtp.gmail.com and port: 587

                 

 

Step 3: Create a CAP Application

Use the CAP Template Wizard in DevSpace to generate your project. Once created:

Define a service with a function for sending emails in .cds:service CatalogService {
function sendMail() returns String;
}

 

Implement it in .js:const cds = require(‘@sap/cds’);

const SapCfMailer = require(“sap-cf-mailer”).default;

module.exports = cds.service.impl(function () {

this.on(‘sendMail’, async () => {

try {

const transporter = new SapCfMailer(“GmailSMTP”); // Match your destination

const result = await transporter.sendMail({

to: “”, //to list separated by comma

cc: “”, //cc list separated by comma

subject: “Test Mail from BTP System”,

html: “Hello from CAP!”,

attachments: []

});

return `Email sent successfully`;

} catch (error) {

console.error(‘Error sending email:’, error);

return `Error sending email: ${error.message}`;

}

});

});

 

Install the mailer library:

npm i sap-cf-mailer

 

Step 4: Bind Services in Cloud Foundry

If your CAP app is new, some required services—like destination services—might not exist yet. In that case:

Build and deploy your MTA project. Even if the deployment isn’t fully successful, the necessary services will still be created.

       

       2.Go to Cloud Foundry → Services and bind your app to the newly created destinations.

          

         3.After binding, your .env file will automatically include the credentials you need.

 If you’re working with an existing app, you can skip the MTA build ,just bind the Cloud Foundry services, and you’re ready to go.

Let’s test: Run cds watch and call sendMail from your browser. Check your inbox, your screenshot will show the email arriving.

 

Step 5: Sending HTML Emails

You can send nicely formatted emails with HTML. Just store your HTML in a variable and pass it to the html property:

 

this.on(‘sendMail’, async () => {

try {

const transporter = new SapCfMailer(“GmailSMTP”); //enter destination name

const htmlContent = `<!DOCTYPE html>

<html>

<body style=”margin:0;padding:0;background:#f6f7fb;font-family:Arial,Helvetica,sans-serif;”>

<table role=”presentation” width=”100%” cellspacing=”0″ cellpadding=”0″ style=”background:#f6f7fb;”>

<tr>

<td align=”center” style=”padding:24px;”>

<table role=”presentation” width=”600″ cellspacing=”0″ cellpadding=”0″ style=”background:#ffffff;border-radius:12px;padding:24px;”>

<tr>

<td>

<h2 style=”margin:0 0 12px;font-size:20px;color:#111;”>Hello Mahesh 👋</h2>

<p style=”margin:0 0 16px;color:#333;line-height:1.5;”>

This is a quick test email from your SAP BTP CAP app. If you can read this, your mail setup works!

</p>

<p style=”margin:0 0 24px;”>

<a href=”https://example.com” style=”display:inline-block;text-decoration:none;padding:10px 16px;border-radius:8px;background:#2563eb;color:#fff;”>

View Details

</a>

</p>

<p style=”margin:0;color:#666;font-size:12px;”>

— CAP Mailer • <span style=”color:#999;”>Do not reply</span>

</p>

</td>

</tr>

</table>

<p style=”color:#999;font-size:12px;margin:12px 0 0;”>© 2025 Your Company</p>

</td>

</tr>

</table>

</body>

</html>

`;

const result = await transporter.sendMail({

to: “”,

cc: “”,

subject: “Test Mail from BTP System”,

html: htmlContent,

attachments: []

});

return `Email sent successfully w `;

} catch (error) {

console.error(‘Error sending email:’, error);

return `Error sending email: ${error.message}`;

}

});

Let’s test: Run cds watch and call sendMail from your browser. Check your inbox—your screenshot will show the email arriving.

 

Step 6: Sending Attachments

To attach files, convert them to Base64 and include them in the attachments array:

 

this.on(‘sendMail’, async () => {

try {

const transporter = new SapCfMailer(“GmailSMTP”); //enter destination name

const base64pdf=`JVBERi0xLjUKJeLjz9MKMSAwIG9iago8PC9UeXBlL1BhZ2UvUGFyZW50IDIgMCBSL1Jlc291

cmNlcyA8PC9Gb250IDw8L0YxIDMgMCBSPj4+Pi9NZWRpYUJveFswIDAgNjEyIDc5Ml0vQ29u

dGVudHMgNCAwIFI+PgplbmRvYmoKMiAwIG9iago8PC9UeXBlL1BhZ2VzL0tpZHNbMSAwIFJd

L0NvdW50IDE+PgplbmRvYmoKMyAwIG9iago8PC9UeXBlL0ZvbnQvU3ViVHlwZS9UcnVlVHlw

ZS9CYXNlRm9udC9UaW1lcy1Sb21hbi9FbmNvZGluZy9XaW5BbnNpRW5jb2Rpbmc+PgplbmRv

YmoKNCAwIG9iago8PC9MZW5ndGggNjY+PnN0cmVhbQpCBiAgICAgICAgICAgIApIZWxsbyBX

b3JsZCEKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjw8L1R5cGUvQ2F0YWxvZy9QYWdlcyAy

IDAgUj4+CmVuZG9iagp4cmVmCjAgNgowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDAxMTkg

MDAwMDAgbiAKMDAwMDAwMDY2IDAwMDAwIG4gCjAwMDAwMDAxMzAgMDAwMDAgbiAKMDAwMDAw

MDE5MSAwMDAwMCBuIAowMDAwMDAwMjU3IDAwMDAwIG4gCnRyYWlsZXIKPDwvUm9vdCA1IDAg

Ui9TaXplIDY+PgpzdGFydHhyZWYKMjg4CiUlRU9G

` ;

const result = await transporter.sendMail({

to: “”,

cc: “”,

subject: “Test Mail from BTP System”,

html: “Hope this goes well.”,

attachments: [{ filename: “sample.pdf”, content: base64pdf, encoding: “base64” }]

});

return `Email sent successfully w `;

} catch (error) {

console.error(‘Error sending email:’, error);

return `Error sending email: ${error.message}`;

}

});

 

 

Conclusion:

By following these steps, we’ve successfully sent emails directly from our SAP CAP application. The setup allows you to send plain text or richly formatted HTML emails, include multiple recipients, CCs, or attachments, and work securely using Gmail App Passwords, avoiding less secure app issues.

Everything we tested—sending a basic email, an HTML email, and attaching a PDF—worked smoothly, showing that this approach is ready for real-world use. Your CAP app can now reliably send notifications, reports, or alerts to users

 

 

 

 

 

 

​  Sending Emails from SAP CAP Applications with Any SMTP ProviderStep 1: Prepare Your Mail AccountEnable 2-Step Verification if your provider requires it (Gmail does).Generate an App Password or special SMTP password. This is safer than using your regular password.        Navigate to Google Account->Security            Search application password        Step 2 : Create a Destination in SAP BTP CockpitA destination in BTP stores connection details to external systems (in this case, Gmail SMTP).Here’s what you do:Go to your SAP BTP Cockpit → Destinations.Create a new destination with:Name: GmailSMTPType: SMTPAuthentication: BasicAuthenticationUser: Password: The 16-character App Password generated from GoogleAdditional properties like host: smtp.gmail.com and port: 587                  Step 3: Create a CAP ApplicationUse the CAP Template Wizard in DevSpace to generate your project. Once created:Define a service with a function for sending emails in .cds:service CatalogService {
function sendMail() returns String;
} Implement it in .js:const cds = require(‘@sap/cds’);

const SapCfMailer = require(“sap-cf-mailer”).default;

module.exports = cds.service.impl(function () {

this.on(‘sendMail’, async () => {

try {

const transporter = new SapCfMailer(“GmailSMTP”); // Match your destination

const result = await transporter.sendMail({

to: “”, //to list separated by comma

cc: “”, //cc list separated by comma

subject: “Test Mail from BTP System”,

html: “Hello from CAP!”,

attachments: []

});

return `Email sent successfully`;

} catch (error) {

console.error(‘Error sending email:’, error);

return `Error sending email: ${error.message}`;

}

});

}); Install the mailer library:npm i sap-cf-mailer Step 4: Bind Services in Cloud FoundryIf your CAP app is new, some required services—like destination services—might not exist yet. In that case:Build and deploy your MTA project. Even if the deployment isn’t fully successful, the necessary services will still be created.              2.Go to Cloud Foundry → Services and bind your app to the newly created destinations.                   3.After binding, your .env file will automatically include the credentials you need. If you’re working with an existing app, you can skip the MTA build ,just bind the Cloud Foundry services, and you’re ready to go.Let’s test: Run cds watch and call sendMail from your browser. Check your inbox, your screenshot will show the email arriving. Step 5: Sending HTML EmailsYou can send nicely formatted emails with HTML. Just store your HTML in a variable and pass it to the html property: this.on(‘sendMail’, async () => {

try {

const transporter = new SapCfMailer(“GmailSMTP”); //enter destination name

const htmlContent = `<!DOCTYPE html>

<html>

<body style=”margin:0;padding:0;background:#f6f7fb;font-family:Arial,Helvetica,sans-serif;”>

<table role=”presentation” width=”100%” cellspacing=”0″ cellpadding=”0″ style=”background:#f6f7fb;”>

<tr>

<td align=”center” style=”padding:24px;”>

<table role=”presentation” width=”600″ cellspacing=”0″ cellpadding=”0″ style=”background:#ffffff;border-radius:12px;padding:24px;”>

<tr>

<td>

<h2 style=”margin:0 0 12px;font-size:20px;color:#111;”>Hello Mahesh 👋</h2>

<p style=”margin:0 0 16px;color:#333;line-height:1.5;”>

This is a quick test email from your SAP BTP CAP app. If you can read this, your mail setup works!

</p>

<p style=”margin:0 0 24px;”>

<a href=”https://example.com” style=”display:inline-block;text-decoration:none;padding:10px 16px;border-radius:8px;background:#2563eb;color:#fff;”>

View Details

</a>

</p>

<p style=”margin:0;color:#666;font-size:12px;”>

— CAP Mailer • <span style=”color:#999;”>Do not reply</span>

</p>

</td>

</tr>

</table>

<p style=”color:#999;font-size:12px;margin:12px 0 0;”>© 2025 Your Company</p>

</td>

</tr>

</table>

</body>

</html>

`;

const result = await transporter.sendMail({

to: “”,

cc: “”,

subject: “Test Mail from BTP System”,

html: htmlContent,

attachments: []

});

return `Email sent successfully w `;

} catch (error) {

console.error(‘Error sending email:’, error);

return `Error sending email: ${error.message}`;

}

});Let’s test: Run cds watch and call sendMail from your browser. Check your inbox—your screenshot will show the email arriving. Step 6: Sending AttachmentsTo attach files, convert them to Base64 and include them in the attachments array: this.on(‘sendMail’, async () => {

try {

const transporter = new SapCfMailer(“GmailSMTP”); //enter destination name

const base64pdf=`JVBERi0xLjUKJeLjz9MKMSAwIG9iago8PC9UeXBlL1BhZ2UvUGFyZW50IDIgMCBSL1Jlc291

cmNlcyA8PC9Gb250IDw8L0YxIDMgMCBSPj4+Pi9NZWRpYUJveFswIDAgNjEyIDc5Ml0vQ29u

dGVudHMgNCAwIFI+PgplbmRvYmoKMiAwIG9iago8PC9UeXBlL1BhZ2VzL0tpZHNbMSAwIFJd

L0NvdW50IDE+PgplbmRvYmoKMyAwIG9iago8PC9UeXBlL0ZvbnQvU3ViVHlwZS9UcnVlVHlw

ZS9CYXNlRm9udC9UaW1lcy1Sb21hbi9FbmNvZGluZy9XaW5BbnNpRW5jb2Rpbmc+PgplbmRv

YmoKNCAwIG9iago8PC9MZW5ndGggNjY+PnN0cmVhbQpCBiAgICAgICAgICAgIApIZWxsbyBX

b3JsZCEKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjw8L1R5cGUvQ2F0YWxvZy9QYWdlcyAy

IDAgUj4+CmVuZG9iagp4cmVmCjAgNgowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDAxMTkg

MDAwMDAgbiAKMDAwMDAwMDY2IDAwMDAwIG4gCjAwMDAwMDAxMzAgMDAwMDAgbiAKMDAwMDAw

MDE5MSAwMDAwMCBuIAowMDAwMDAwMjU3IDAwMDAwIG4gCnRyYWlsZXIKPDwvUm9vdCA1IDAg

Ui9TaXplIDY+PgpzdGFydHhyZWYKMjg4CiUlRU9G

` ;

const result = await transporter.sendMail({

to: “”,

cc: “”,

subject: “Test Mail from BTP System”,

html: “Hope this goes well.”,

attachments: [{ filename: “sample.pdf”, content: base64pdf, encoding: “base64” }]

});

return `Email sent successfully w `;

} catch (error) {

console.error(‘Error sending email:’, error);

return `Error sending email: ${error.message}`;

}

});  Conclusion:By following these steps, we’ve successfully sent emails directly from our SAP CAP application. The setup allows you to send plain text or richly formatted HTML emails, include multiple recipients, CCs, or attachments, and work securely using Gmail App Passwords, avoiding less secure app issues.Everything we tested—sending a basic email, an HTML email, and attaching a PDF—worked smoothly, showing that this approach is ready for real-world use. Your CAP app can now reliably send notifications, reports, or alerts to users        Read More Technology Blog Posts by Members articles 

#SAP

#SAPTechnologyblog

You May Also Like

More From Author