Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?

How to trigger an email on database update in Flutter with SendGrid

E-mail is a medium of communication used to ship and obtain electronic-based recordsdata like textual content paperwork, photographs, movies, and so on. Past the normal use case, it has develop into an important software utilized by builders to watch and talk their functions’ standing.

On this put up, we are going to learn to use Appwrite Perform and SendGrid to set off an electronic mail when a database is up to date in Flutter.



Know-how overview

Appwrite Function is a service that lets us use Appwrite server performance by executing a customized code utilizing a language of alternative like Node.js, Python, PHP, Dart, or Java.

SendGrid is a cloud-based electronic mail advertising software builders and entrepreneurs use to handle mailing lists, A/B testing, predefined templates, and picture libraries utilized in marketing campaign administration and viewers engagement.



GitHub hyperlinks

The challenge supply codes are beneath:



Stipulations

To comply with alongside on this tutorial, the next necessities apply:



Arrange SendGrid as an electronic mail supplier

To get began, we have to log into our Sendgrid account and create a sender id for sending emails. To do that, click on the Create a Single Sender button and fill within the required particulars.


Fill details

We will even be required to confirm the e-mail stuffed in because the sender’s id.

Subsequent, we have to create an API Key to securely entry our SendGrid account and ship emails from a shopper. To do that, navigate to the API Key tab beneath the Settings menu and click on the Create API Key button.

Create API Key

Enter appwrite_sendgrid because the API Key Identify and click on the Create & View button.

Input detail and create

SendGrid will generate an API Key. We have to copy and maintain the generated key, as it would turn out to be useful when establishing our Appwrite perform.



Combine Appwrite Perform with SendGrid

Enabling Dart runtime in Appwrite
By default, Dart just isn’t included as a part of the Appwrite runtime. To allow Dart as a supported runtime, we first must navigate to the listing created once we put in Appwrite and edit the .env file by including dart-2.17 as proven beneath:

Appwrite folder with .env file

//remaining env variable goes right here

_APP_FUNCTIONS_RUNTIMES=node-16.0,php-8.0,python-3.9,ruby-3.0,dart-2.17
Enter fullscreen mode

Exit fullscreen mode

Updated runtime with Dart support

Lastly, we have to sync the modifications we made on the .env file with our Appwrite server. To do that, we should run the command beneath contained in the appwrite listing.

docker compose up -d --force-recreate
Enter fullscreen mode

Exit fullscreen mode

Create Appwrite project
With our Appwrite occasion up and operating, we will now create a challenge that our perform will use to combine SendGrid to ship emails. To do that, we first must navigate to the specified listing and run the command beneath:

mkdir appwrite_sendgrid && cd appwrite_sendgrid
Enter fullscreen mode

Exit fullscreen mode

The command creates a challenge folder known as appwrite_sendgrid and navigates into the folder.

Secondly, we have to log into the Appwrite server utilizing the CLI.

appwrite login
Enter fullscreen mode

Exit fullscreen mode

We shall be prompted to enter our electronic mail and password. We have to use the credentials we used to enroll to the Appwrite console.

Lastly, we have to create a brand new Appwrite challenge utilizing the command beneath:

appwrite init challenge
Enter fullscreen mode

Exit fullscreen mode

We shall be prompted with some questions on the right way to arrange our challenge, and we will reply as proven beneath:

How would you want to begin? <choose "Create a brand new challenge">
What would you want to call your challenge? <enter "appwrite_sendgrid">
What ID would you prefer to have for your challenge? (distinctive()) <press enter>
Enter fullscreen mode

Exit fullscreen mode

Create Appwrite Perform contained in the project
With our challenge setup, we will proceed to create a perform by operating the command beneath:

appwrite init perform
Enter fullscreen mode

Exit fullscreen mode

We will even be prompted with some questions on the right way to arrange our perform; we will reply as proven beneath:

What would you want to call your perform? <enter "appwrite_sendgrid">
What ID would you prefer to have for your perform? (distinctive()) <press enter>
What runtime would you want to make use of? <scroll to dart-2.17 and press enter>
Enter fullscreen mode

Exit fullscreen mode

The command will create a starter Dart challenge.

Starter project

Secondly, we have to set up the required dependency by navigating to pubspec.yaml file and add SendGrid SDK to the dependencies part.

sendgrid_mailer: ^0.1.3
Enter fullscreen mode

Exit fullscreen mode

Install dependency

We additionally want to put in the required dependency by operating the command beneath:

cd features/appwrite_sendgrid/
dart pub get
Enter fullscreen mode

Exit fullscreen mode

Thirdly, we have to modify the principal.dart file contained in the lib folder as proven beneath:

import 'package deal:dart_appwrite/dart_appwrite.dart';
import 'package deal:sendgrid_mailer/sendgrid_mailer.dart';

Future<void> begin(last req, last res) async {
  Shopper shopper = Shopper();

  last mailer = Mailer('SENDGRID API KEY');
  last toAddress = Handle('SEND TO EMAIL');
  last fromAddress = Handle('SENDER EMAIL CREATED ON SENDGRID');
  last content material =
      Content material('textual content/plain', 'Appwrite Database efficiently up to date');
  last topic = 'Database Replace Alert!';
  last personalization = Personalization([toAddress]);

  last electronic mail =
      E-mail([personalization], fromAddress, topic, content material: [content]);
  mailer.ship(electronic mail).then((outcome) {
    print(outcome);
  }).catchError((onError) {
    print('error');
  });

  res.json({
    'information': "testing emails",
  });
}
Enter fullscreen mode

Exit fullscreen mode

The snippet above does the next:

  • Imports the required dependencies
  • Configures SendGrid mail shopper by specifying the API Key, to emails, from emails, electronic mail content material, and electronic mail topic
  • Sends the e-mail utilizing the configured shopper

Lastly, we have to navigate again to the challenge terminal after which deploy our perform.

cd ../..
appwrite deploy perform
Enter fullscreen mode

Exit fullscreen mode

We will even be prompted to the features to deploy. We are able to choose the appwrite_sendgrid perform by urgent the spacebar key to mark and the enter key to choose it.

Sample of a deployed function

We are able to additionally verify the deployment by navigating to the Perform tab on the Appwrite console,

Deployed function

Add occasion assist to Appwrite Perform
Subsequent, we have to add an occasion (database replace) to our Appwrite Perform. The occasion will set off the perform anytime the database is up to date. To do that, navigate to the Settings tab, click on the Add Occasion button, and choose paperwork.replace possibility, and click on the Add Occasion. Then lastly, click on the Replace button to avoid wasting modifications.

Click settings
Add Event
Update



Create a Flutter app

With our perform deployed and listening for occasion modifications on the database, we will now proceed to arrange a Flutter challenge.

To get began, we have to clone the challenge by navigating to the specified listing and operating the command beneath:

git clone https://github.com/Mr-Malomz/flutter_sendgrid.git && cd flutter_sendgrid
Enter fullscreen mode

Exit fullscreen mode

The challenge logic to replace a database and UI has already been arrange. Under are some essential recordsdata to notice within the lib listing:

screens/dwelling.dart: Incorporates the UI for updating a database.

utils: Incorporates Appwrite constants and Mannequin. We’ll replace this file shortly.

user_service.dart: Incorporates software logic for updating the database.

Operating the project
First, we have to set up the challenge dependencies by operating the command beneath:

flutter pub get
Enter fullscreen mode

Exit fullscreen mode

Then, run the challenge utilizing the command beneath:

flutter run
Enter fullscreen mode

Exit fullscreen mode

The command above will run the applying on the chosen system.

Running app

Create a Database and Add Pattern Knowledge
Subsequent, we have to create a database with the corresponding assortment, doc, and add pattern information as proven beneath:

collection

Add Platform assist
So as to add assist for our Flutter app, navigate to the Residence menu, click on on the Add Platform button, and choose New Flutter App.

Add platform
Select new Flutter app

Relying on the system on which we’re operating our Flutter software, we will modify it as proven beneath.

iOS
To acquire our Bundle ID, we will navigate utilizing the trail beneath:
ios > Runner.xcodeproj > challenge.pbxproj

Open the challenge.pbxproj file and seek for PRODUCT_BUNDLE_IDENTIFIER.

iOS

Subsequent, open the challenge listing on Xcode, open the Runner.xcworkspace folder within the app’s iOS folder, choose the Runner challenge within the Xcode challenge navigator, choose the Runner goal in the principle menu sidebar, after which choose iOS 11 within the deployment data’s goal.

Change deployment target

Android
To get our package deal identify, we will navigate to an XML file utilizing the trail beneath:
android > app > src > debug > AndroidManifest.xml

Open the AndroidManifest.xml file and duplicate the package deal worth.

Android

Subsequent, we have to modify the AndroidManifext.xml as proven beneath:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package deal="com.instance.real_time_comm">
    <uses-permission android:identify="android.permission.INTERNET"/>
    <software ...>
    <exercise android:identify="com.linusu.flutter_web_auth.CallbackActivity" android:exported="true">
      <intent-filter android:label="flutter_web_auth">
        <motion android:identify="android.intent.motion.VIEW" />
        <class android:identify="android.intent.class.DEFAULT" />
        <class android:identify="android.intent.class.BROWSABLE" />
        <information android:scheme="appwrite-callback-[PROJECT_ID]" />
      </intent-filter>
    </exercise>
  </software>
</manifest>
Enter fullscreen mode

Exit fullscreen mode

We additionally want to switch the highlighted [PROJECT_ID] with our precise Appwrite challenge ID.

Placing all of it collectively
With that performed, we have to navigate to the utils.dart file so as to add the required IDs and endpoint.

class AppConstant {
  last String databaseId = "DATABASE ID HERE";
  last String projectId = "PROEJCT ID HERE";
  last String collectionId = "COLLECTION ID";
  last String userId = "USER ID"; //that is the ID of the pattern information created
  last String endpoint = "ENDPOINT";
}

class Consumer {
  String identify;

  Consumer({required this.identify});

  Map<dynamic, dynamic> toJson() {
    return {'identify': identify};
  }
}
Enter fullscreen mode

Exit fullscreen mode

With that performed, we restart the applying utilizing the code editor or run the command beneath:

flutter run
Enter fullscreen mode

Exit fullscreen mode

https://media.giphy.com/media/e77IjfyDqwLzKbW0rW/giphy.gif

We are able to validate the despatched electronic mail by checking Appwrite Perform log and SendGrid exercise tab

Appwrite log
SendGrid activity

This put up mentioned the right way to create and configure Appwrite Perform to ship emails utilizing SendGrid when a database is up to date. Appwrite Perform permits builders to write down and ship software program of their language of alternative.

These sources may be useful:

Add a Comment

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?