Blog

How to Send Email From Your Mobile, Browser, or Desktop App

by on September 1, 2019

Sending an email is a very common operation for many applications. For most of them, it is the server-side that is responsible for delivering an email message. Backendless makes it trivially easy to deliver a branded email (meaning it will look like it was sent by your app) in the plain text or HTML formats (or both).

Consider the following code, which sends an HTML-formatted email message:

       AsyncCallback sendEmailCallback = new AsyncCallback<MessageStatus>() {
           @Override
           public void handleResponse(MessageStatus response) {
               Log.i(TAG, "ASYNC: HTML email has been sent");
           }
    
           @Override
           public void handleFault(BackendlessFault fault) {
               Log.e(TAG, fault.getMessage());
           }
       };
    
       String subject = "Hello from Backendless! (Async call)";
       String body = "This is an HTML email sent by an <b>asynchronous</b> API call from a <a href="\"http://backendless.com\"">Backendless</a> backend";
       String recipient = "info@backendless.com";
       Backendless.Messaging.sendHTMLEmail(subject, body, recipient, sendEmailCallback);

       val sendEmailCallback = object : AsyncCallback<MessageStatus> {
           override fun handleResponse(response: MessageStatus) {
               Log.i(TAG, "ASYNC: HTML email has been sent")
           }
    
           override fun handleFault(fault: BackendlessFault) {
               Log.e(TAG, fault.message)
           }
       }
    
       val subject = "Hello from Backendless! (Async call)"
       val body = "This is an HTML email sent by an <b>asynchronous</b> API call from a <a href="\"http://backendless.com\"">Backendless</a> backend"
       val recipient = "info@backendless.com";
       Backendless.Messaging.sendHTMLEmail(subject, body, recipient, sendEmailCallback)

    NSString *subject = @"Hello from Backendless! (Async call)";
    NSString *recipient = @"info@backendless.com";
        
    EmailBodyparts *emailBodyParts = [EmailBodyparts new];
    emailBodyParts.htmlMessage = @"This is an HTML email sent by an <b>asynchronous</b> API call from a <a href="\"http://backendless.com\"">Backendless</a> backend";
        
    [Backendless.shared.messaging sendEmailWithSubject:subject bodyparts:emailBodyParts recipients:@[recipient] attachments:nil responseHandler:^(MessageStatus *messageStatus) {
        NSLog(@"ASYNC: HTML email has been sent");
    } errorHandler:^(Fault *fault) {
        NSLog(@"Error: %@", fault.message);
    }];

    let subject = "Hello from Backendless! (Async call)"
    let recipient = "info@backendless.com"
            
    let emailBodyParts = EmailBodyparts()
    emailBodyParts.htmlMessage = "This is an HTML email sent by an <b>asynchronous</b> API call from a <a href="\"http://backendless.com\"">Backendless</a> backend"
            
    Backendless.shared.messaging.sendEmail(subject: subject, bodyparts: emailBodyParts, recipients: [recipient], attachments: nil, responseHandler: { messageStatus in
        print("ASYNC: HTML email has been sent")
    }, errorHandler: { fault in
        print("Error: \(fault.message ?? "")")
    })

    const Backendless = require('backendless')
    /*
     Or use `import Backendless from 'backendless'` for client side.
     If you don't use npm or yarn to install modules, you can add the following line
     <script src="//api.backendless.com/sdk/js/latest/backendless.min.js"></script>
     to your index.html file and use the global Backendless variable.
    */
    
    Backendless.initApp('YOUR_APP_ID', 'YOUR_JS_API_KEY')
    
    const bodyParts = new Backendless.Bodyparts()
    
    bodyParts.htmlmessage = `
      This is an <b>HTML email</b> sent from a <a href="\"http://backendless.com\"">Backendless</a> 
      backend`
    
    const subject = 'Hello from Backendless!'
    const recipient = 'info@backendless.com'
    
    const onSuccess = status => {
      console.log('HTML email has been sent')
    }
    
    const onError = error => {
      console.error('Server reported an error: ', error.message)
      console.error('error code: ', error.code)
      console.error('http status: ', error.status)
    }
    
    Backendless.Messaging.sendEmail(subject, bodyParts, [recipient])
      .then(onSuccess)
      .catch(onError)
    

       String subject = "Hello from Backendless! (Async call)";
       String body = "This is an HTML email sent by an <b>asynchronous</b> API call from a <a href="\"http://backendless.com\"">Backendless</a> backend";
       String recipient = "info@backendless.com";
    
       Backendless.Messaging.sendHTMLEmail(subject, body, [recipient]).then(
         (response) => print("ASYNC: HTML email has been sent"));

    The code above sends an HTML-formatted email to one recipient. You can also create an array of email addresses to use instead. That way, an email will be delivered to a group of recipients.

    If you run the code above without making any configuration changes to your Backendless backend, you will receive the following error:

    BackendlessException{ code: '5045', message: 'Cannot send email with the default Email Settings. Change the Email Settings in the console and try again' }

    This error occurs when you try using the functionality for sending an email and do not change the Email Settings. By default, every Backendless backend is configured to use our special email account. That account does not let you use the API demonstrated above – you need to change it to your SMTP account. To do that:

    1. Login to Backendless Console, select your app and click the Manage icon.
    2. Scroll down to the Email Settings section.
    3. Enter the name you would like to use in the emails sent out by Backendless. Also, enter the email address (which is the userid) and password used to authenticate against the SMTP server.
    4. Before you save the data, click the Test button to validate the credentials.
    5. Click the Save button to save the new settings.

    Below is a screenshot of the settings after making the changes described above:

    Now when we run the same code, we get the following output:

    SYNC: HTML email has been sent
    ASYNC: HTML email has been sent

    When the email arrives, it looks exactly as expected – an HTML-formatted email:

    There are plenty of methods to deliver email messages in different formats to one or more recipients. You can learn more about the API to send email from the documentation.

    Enjoy!

    Leave a Reply